I want to create a following matrix using nested loops
Show older comments
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
on 4 Jun 2022
Why do you want to use for loops exactly? What pattern is in this matrix?
Walter Roberson
on 4 Jun 2022
it would make more sense to me if the last entry was 40 instead of 41...
Accepted Answer
More Answers (2)
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
Shivani Galande
on 4 Jun 2022
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.
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]
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
(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..
Categories
Find more on Polynomials 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!