Sum of rows in Magic square using nested for-loops
Show older comments
Hello there,
In my task, we're supposed to create a Magic matrix of 10 and find out the sum of each individual rows before creating a 10x1 vector output displaying the results of each rows. I understand that this can be done simply by using
for i = 1:1:numel(10);
sumRow = sum(matrix, 2);
end
but we are required to do it with nested for-loops instead. Can somebody kindly help me with this? Thank you!
2 Comments
Guillaume
on 17 Nov 2018
Actually, the whole lot can be done without a single loop and would be the efficient way to do it in matlab.
If you are asked to use double for loop, I would thing you have to convert that sum into a loop.
A pointless exercise, in my opinion. There are plenty of ways to teach loops in matlab that don't involve teaching bad habits as well.
Note that as written your loop is pointless. numel(10) is 1.
Stephen23
on 17 Nov 2018
"I understand that this can be done simply..."
without a loop:
sum(matrix,2)
Answers (1)
madhan ravi
on 17 Nov 2018
Edited: madhan ravi
on 17 Nov 2018
without loop is better:
matrix=magic(10);
sumRow=sum(matrix,2)
with loop (inefficient) according to your requirement:
matrix=magic(10);
n=size(matrix,1);
sumRow = cell(1,n)
for i = 1:n
sumRow{i} = sum(matrix(i,:), 2);
end
sumRow = cell2mat(sumRow{:})
3 Comments
Stephen23
on 17 Nov 2018
"...we are required to do it with nested for-loops..."
Bruno Luong
on 17 Nov 2018
and furthermore "we" means OP, not one of us
Kiden Sizhao Wang
on 17 Nov 2018
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!