필터 지우기
필터 지우기

For cycle to create multiple matrixes

조회 수: 1 (최근 30일)
Pedro Silva
Pedro Silva 2012년 4월 4일
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