Message Boards Message Boards

0
|
5241 Views
|
7 Replies
|
4 Total Likes
View groups...
Share
Share this post:

How to declare larger Matrix?

Posted 10 years ago
POSTED BY: Ulrich Hauser
7 Replies

Hi there,

the following might help. I avoid using For-loops etc because it is faster.

First I generate an empty matrix of the desired dimensions:

matrix = ConstantArray[0, {9, 9, 6}];

This generates the matrix with all zeros. Let's suppose I have a couple of index combinations for which the entries are "1". I am too lazy to make some combinations up so I generate random index combinations:

nonzero = Table[{RandomInteger[{1, 9}], RandomInteger[{1, 9}], RandomInteger[{1, 6}]}, {k, 1, 10}];

Now I can populate the matrix with the "1's" at the given positions:

Set[Part[matrix, #[[1]], #[[2]], #[[3]]], 1] & /@ nonzero

I understand that this is quite different from the standard programming paradigm in say Fortran or C. If you insist in using a for loop this would work:

For[i = 1, i <= Length[nonzero], i++, matrix[[nonzero[[i, 1]], nonzero[[i, 2]], nonzero[[i, 3]]]] = 1]

Cheers,

M.

POSTED BY: Marco Thiel

I think Instead of

Set[Part[matrix, #[[1]], #[[2]], #[[3]]], 1] & /@ nonzero 

This is a little simpler:

matrix2 = ReplacePart[matrix2, nonzero -> 1] 
POSTED BY: Nasser M. Abbasi

That is true, but the first method is faster:

enter image description here

Cheers,

M.

POSTED BY: Marco Thiel

Thanks for your help Marco and Nasser, That ConstantArray was exactly what I was looking for. Now I am stuck with that For loop. It does not want to pass on the value. There must be some trick to it. Here the procedure and with the result in the Attachment. Thanks so much. (Pls take note that with my 70+ years I am mentally not so flexible anymore.)

n = ConstantArray[1, {3, 4}];

r = 2;

For[s = 1, 4, s++, n[[r, s]] = RandomInteger[{1, 9}]];

n // MatrixForm

Attachments:
POSTED BY: Ulrich Hauser

Hi,

the last one is just because of a little syntax error in the for loop.

n = ConstantArray[1, {3, 4}];
r = 2;
For[s = 1, s <= 4, s++, n[[r, s]] = RandomInteger[{1, 9}]];

will work.

Cheers,

M.

POSTED BY: Marco Thiel

Thank you Marco for making my day. Somehow Iam still fixed in the old languages. Anyhow, I can start now to work on my little project. I will be back on the forum when I hit the next road block. All the best to you Ulrich

POSTED BY: Ulrich Hauser

No problem at all. If you encounter any other issue I would be glad to help.

Best wishes,

Marco

POSTED BY: Marco Thiel
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract