Nested for Loop needed

5 次查看(过去 30 天)
Tom
Tom 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