Clear Filters
Clear Filters

For cycle to create multiple matrixes

1 view (last 30 days)
Pedro Silva
Pedro Silva on 4 Apr 2012
Hey everyone!
Im trying to create 35 5*7 matrixes, all made up by zeros and one 1 in each position.
For example, the first matrix would be
[1 0 0 0 0 0 0; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 ; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0]
the second would be
[0 1 0 0 0 0 0; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 ; 0 0 0 0 0 0 0; 0 0 0 0 0 0 0] and so on!
What i tried was:
H(:,:,1)=zeros(5,7);
for n=2:36
H(:,:,n)=zeros(5,7);
for r=1:5
for c=1:7
H(r,c,n)=1;
end
end
end
but this doesnt work since I end up with 35 matrices made up by ones.
Help please! I am out of ideas!
  2 Comments
Pedro Silva
Pedro Silva on 4 Apr 2012
Ofcourse I could do it manually, but it isn't either pratical or smart
Geoff
Geoff on 4 Apr 2012
What you actually want to do in this loop is turn 'n' into a single row 'r' and column 'c', and then set only that row and column to 1.
r = 1 + floor((n-1) / 5);
c = 1 + mod(n-1, 7);

Sign in to comment.

Answers (2)

the cyclist
the cyclist on 4 Apr 2012
Here is a concise way to do it:
H = zeros(5,7,35);
H(1:36:end)=1;
This takes advantage of "linear indexing" to access the elements of the array as if they were in one long vector (which they are, in memory).
Also, be aware of the ability to make "sparse" arrays in MATLAB, which looks like it might be appropriate for you. See
doc sparse
for more info.

Geoff
Geoff on 4 Apr 2012
This conceptually is like turning each row of the 35x35 identity into a 5x7 matrix.
H = reshape(eye(35), 5, 7, 35);
But that's column-first precedence, and you obviously want the rows so you need to transpose a 7x5...
H = permute(reshape(eye(35), 7, 5, 35), [2 1 3]);
You can use the permute call on the cyclist's answer, which also suffers from the column-first thing.
  4 Comments
João Viveiros
João Viveiros on 10 Apr 2012
Can you just tell me how would you do that for 2 ones? if i could see a code for one one, and two ones, i think i can do the rest.
Walter Roberson
Walter Roberson on 10 Apr 2012
You can use an "odometer" like function. See http://www.mathworks.com/matlabcentral/answers/29662-generate-points-sorted-by-distance

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!