Group Abstract Group Abstract

Message Boards Message Boards

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

How to declare larger Matrix?

Posted 11 years ago
POSTED BY: Ulrich Hauser
7 Replies
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
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

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
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard