Nested for loop help needed
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi guys, can anyone help me out with this one:
x =
A B C
D E F
G H I
J K L
I need to produce a loop which for this matrix, would output 3 numbers defined as:
1st = DG + EF + FI
2nd = DJ + EK + FL
3rd = GJ + HK + IL
1st = the elements of the second row * the elements of the third
2nd = the elements of the second row * the elements of the fourth
3rd = the elements of the third row * the element of the fourth
So you see, the second row is held and multiplied with all rows below it. Then the loop moves down so the third row is held and multiplied with all rows below it.
Also it's required that the loop can accommodate a matrix with any number of columns, but always three rows. If anyone's interested, the number of permutations = ((N-1)(N-2)) / 2 where N = number of columns
Could anyone help me in figuring this out? I've been getting tangled up in loops for a while now, but I think the problem is probably quite simple for someone with experience of such things.
Kind regards,
Tom
댓글 수: 8
Image Analyst
2013년 10월 31일
Isn't this essentially the same as http://www.mathworks.com/matlabcentral/answers/104490-nested-for-loop-needed?
답변 (1개)
Cedric
2013년 10월 31일
편집: Cedric
2013년 10월 31일
Following up on comments..
We usually try to avoid explicit loops when we can implement a matrix/vector approach. The latter is much more efficient than looping, especially looping over both rows and columns. My hints were showing how to get rid of the loop over columns:
X = ...
number1 = sum( X(2,:) .* X(3,:) ) ;
number2 = sum( X(2,:) .* X(4,:) ) ;
number3 = sum( X(3,:) .* X(4,:) ) ;
This is probably the best approach if you have only 4 rows in X, because it avoids the complication of looping over combinations of {2,3,4} taken 2 at a time. A loop for that would be more complex, probably less efficient, and involve more code.
If X had a variable number of rows, say nRow, and you needed to follow the same approach involving rows 2 to nRow, you could do it as follows:
X = randi(10, 6, 8) ; % Example with 6 rows and 8 columns.
combSet = nchoosek( 2:size(X,1), 2 ) ; % Array of all comb. of 2 elements.
results = zeros( size(combSet, 1), 1 ) ; % Prealloc. for results.
for cId = 1 : length( results )
results(cId) = sum( X(combSet(cId,1),:) .* X(combSet(cId,2),:) ) ;
end
With that, you get (you'll have different numbers due to RANDI)
>> X
X =
9 3 10 8 7 8 7 8
10 6 5 10 8 1 4 8
2 10 9 7 8 3 10 2
10 10 2 1 4 1 1 5
7 2 5 9 7 1 5 5
1 10 10 10 2 9 4 7
>> combSet
combSet =
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
>> results
results =
318
257
314
317
200
261
359
168
196
245
Check, taking e.g. combination 3
>> sum( X(2,:) .* X(5,:) )
ans =
314
which is results(3), so it seems to be working.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!