Nested for Loop needed

5 views (last 30 days)
Tom
Tom on 31 Oct 2013
Commented: Image Analyst on 31 Oct 2013
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 Comments
Tom
Tom on 31 Oct 2013
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 on 31 Oct 2013
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.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 31 Oct 2013
Edited: Image Analyst on 31 Oct 2013
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 Comments
Tom
Tom on 31 Oct 2013
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 on 31 Oct 2013
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!