필터 지우기
필터 지우기

Nested for Loop needed

조회 수: 1 (최근 30일)
Tom
Tom 2013년 10월 31일
댓글: Image Analyst 2013년 10월 31일
Hello,
Could anyone enlighten me as to how to produce the for loops required to perform the following:
2 x 3
2 x 4
2 x 5
3 x 4
3 x 5
4 x 5
The numbers actually refer to the rows of a matrix.
I need a loop which starts with the second row, and multiplies it sequentially with every row beneath it, then moves on to the row below and does the same.
Could anyone explain how this would be done for a matrix with 5 rows as above? I'm sure I could generalise it to n rows, but I have been struggling with this for some time now.
Kind regards,
Tom
  댓글 수: 3
Tom
Tom 2013년 10월 31일
I think I have finally solved it:
for j = 2:(n-1)
for i = (j+1):n
dotp(count1,:) = sum(x(j,:).*x(i,:));
count1 = count1 + 1;
end
end
Image Analyst
Image Analyst 2013년 10월 31일
Hmmm... I think the more straightforward way that most people would do it is to use the prod() function, like I did in my answer below.

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

채택된 답변

Image Analyst
Image Analyst 2013년 10월 31일
편집: Image Analyst 2013년 10월 31일
Try this:
clc;
workspace; % Make sure the workspace panel is showing.
m = magic(5)
outMatrix = m; % Initialize.
for row = 2 : size(m, 1)
newRow = prod(m(row:end, :), 1);
outMatrix(row, :) = newRow;
end
% Print to command window:
outMatrix
In the command window:
m =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
outMatrix =
17 24 1 8 15
10120 6480 43225 11760 9504
440 1296 6175 840 594
110 216 475 42 27
11 18 25 2 9
  댓글 수: 2
Tom
Tom 2013년 10월 31일
Thanks for that. I can see what you are saying and I should probably get prod involved. I don't think your solution is final though, because for a matrix with 5 rows, the solution should be (the product of) 3 rows. Whereas her you have an output containing 5 rows.
Image Analyst
Image Analyst 2013년 10월 31일
OK, well you can ignore the first row if you want. But then you said "starts with the second row, and multiplies it sequentially with every row beneath it, then moves on to the row below and does the same" so you'd have new rows like this
newRow2 = row2 .* row3 .* row4 .* row5
newRow3 = row3 .* row4 .* row5
newRow4 = row4 .* row5
newRow5 = row5
That's 4 rows in the new matrix. So I'm not sure how you're getting only 3 rows, unless you just ignore row 5 because it's just there by itself.

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

추가 답변 (0개)

카테고리

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