I want to create a following matrix using nested loops

5 views (last 30 days)
Matrix[1,2,3,4,5;2,4,7,11,16;3,7,14,25,41] Here every row has different logic.How do I use for loop?
  2 Comments
Rik
Rik on 4 Jun 2022
Why do you want to use for loops exactly? What pattern is in this matrix?
Walter Roberson
Walter Roberson on 4 Jun 2022
it would make more sense to me if the last entry was 40 instead of 41...

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 4 Jun 2022
Here is another way where you're not starting with some initial matrix but just starting with an initial matrix of all zeros.
rows = 3;
columns = 5;
Matrix = zeros(rows, columns); % Initialize
for row = 1 : rows
if row == 1
for col = 1 : columns
Matrix(row, col) = col;
end
else
for col = 1 : columns
if col == 1
Matrix(row, col) = row;
else
Matrix(row, col) = Matrix(row, col - 1) + Matrix(row-1, col);
end
end
end
end
Matrix
Matrix = 3×5
1 2 3 4 5 2 4 7 11 16 3 7 14 25 41

More Answers (2)

Sam Chak
Sam Chak on 4 Jun 2022
I'm no good at nested math. Please write the math equations to describe the relationship between the elements of the matrix.
The general idea is to populate the zero matrix in loops
M = zeros(3, 5)
M =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
to become
M = [1 2 3 4 5; 2 4 7 11 16; 3 7 14 25 41]
M =
1 2 3 4 5
2 4 7 11 16
3 7 14 25 41
  2 Comments
Sam Chak
Sam Chak on 4 Jun 2022
I can understand it is not easy at the beginning. But it is definitely something to train your cognitive skills in writing Loops and Conditionals.
If you want to challenge yourself, or at least make it a little extraordinary from your classmates, you can modify @Image Analyst's code to begin from the last ROW. You can submit two solutions.

Sign in to comment.


Image Analyst
Image Analyst on 4 Jun 2022
Edited: Image Analyst on 4 Jun 2022
Here is one way:
Matrix = [1,2,3,4,5;
2,4,7,11,16;
3,7,14,25,41]
Matrix = 3×5
1 2 3 4 5 2 4 7 11 16 3 7 14 25 41
rows = 3;
columns = 5;
m = Matrix; % Initialize
for row = 2 : rows
for col = 2 : columns
m(row, col) = Matrix(row, col - 1) + Matrix(row-1, col);
end
end
m
m = 3×5
1 2 3 4 5 2 4 7 11 16 3 7 14 25 41
(IMPORTANT Note, if this is your homework you could get into trouble submitting my code as your own.)
Be sure to see my other answer where Matrix is all zeros to start with..
Note: You could also do this with the conv2 function.

Community Treasure Hunt

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

Start Hunting!