필터 지우기
필터 지우기

How to use for loop ?

조회 수: 1 (최근 30일)
Sudharsan Srinivasan
Sudharsan Srinivasan 2017년 9월 20일
댓글: Jan 2017년 9월 22일
Let's say I have a matrix A = zeros(1000,500). I have two another matrices of size 2 X 50 each for example B = [1 2 3 .... 50 ; 2 4 6 .... 100] and C = [3 6 9 .... 150 ; 4 8 12 ....200]. Let's say I have another matrix D of same size 2 X 50 with some numbers for example [2 4 2 ... 67 ; 6 9 3 .... 54]. Now I have add up all these random numbers in matrix D into the matrix A only at the positions dictated by the matrix B and C. For example the first row in matrix B and C as in [1 2 3 .... 50] and [3 6 9 .... 150] are the x and y positions/co-ordinate where the first row of random numbers as in [2 4 2 .... 67] are to be added with matrix A. The same thing goes for the second row also. Clearly, I have to add [2 4 2 .... 67] to the matrix A at the positions [(1,3) (2,6) (3,9) .... (50,150)] and similarly add up [6 9 3 .... 54] to the matrix A at the positions [(2,4) (4,8) (6,12) .... (100,200)].
How can I use for loop to code this ?

채택된 답변

Jan
Jan 2017년 9월 20일
It does not matter, if B and C are matrices, but you care about the value of the elements only - correctly?
for k = 1:numel(B)
A(B(k), C(K)) = A(B(k), C(K)) + D(k);
end
This seems to be very easy. Did you try anything else?
  댓글 수: 2
Sudharsan Srinivasan
Sudharsan Srinivasan 2017년 9월 20일
Hi Jan, I used the same as technique as you have mentioned. But what does 'nume1' in your code mean ?
Rik
Rik 2017년 9월 20일
That isn't the number 1, it is the lowercase L. The function numel counts the number of elements of a matrix. It is therefore equivalent to prod(size(B)) or length(B(:))

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Rik
Rik 2017년 9월 20일
편집: Rik 2017년 9월 21일
Why insist on a loop?
A(sub2ind(size(A), B(:), C(:))) = D(:);
That should do the same thing.
Edit: the difference between my solution and Jan's is that mine doesn't work if the indices in B an C are non-unique combinations, which you could check with this:
length(unique([B(:) C(:)],'rows'))==numel(B)
If that is false, you can't use my solution.
if length(unique([B(:) C(:)],'rows'))==numel(B)
%A(B(:),C(:))=D(:);
A(sub2ind(size(A), B(:), C(:))) = D(:);
else
for k = 1:numel(B)
A(B(k), C(K)) = A(B(k), C(K)) + D(k);
end
end
  댓글 수: 3
Rik
Rik 2017년 9월 21일
Good point. I'll edit my answer, thanks for the correction. Every time I make this mistake I think it's odd for Matlab to work in the way it does.
Jan
Jan 2017년 9월 22일
@Rik: I agree that it would be more intuitive to process the indices serially instead of accessing a rectangular sub-matrix.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by