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 件のコメント
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
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.
0 件のコメント
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
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
2012 年 4 月 10 日
You can use an "odometer" like function. See http://www.mathworks.com/matlabcentral/answers/29662-generate-points-sorted-by-distance
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!