For cycle to create multiple matrixes

1 次查看(过去 30 天)
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 个评论
Pedro Silva
Pedro Silva 2012-4-4
Ofcourse I could do it manually, but it isn't either pratical or smart
Geoff
Geoff 2012-4-4
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);

请先登录,再进行评论。

回答(2 个)

the cyclist
the cyclist 2012-4-4
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 2012-4-4
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 个评论
João Viveiros
João Viveiros 2012-4-10
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 2012-4-10
You can use an "odometer" like function. See http://www.mathworks.com/matlabcentral/answers/29662-generate-points-sorted-by-distance

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by