Hi,
I want to compare each element of matrix with 'total 'and check if it is equal.
Code gives error. How can I do that please?
clc
clear
b=[2 2]
t=[1 1 ; 1 1]
total=2;
for v=1:b(1)
rowsum(v,1)=sum(t(v,:));
end
for y=1:b(2)
colsum(v,1)=sum(t(:,v));
end
if rowsum(:,1)==total && colsum(:,1)==total
disp 'yes'
end

 Accepted Answer

No loops needed:
if all(sum(t)==total)
disp('Yes')
end
if all(sum(t,2)==total)
disp('Yes')
end

3 Comments

Thank you, what is the purpose of using 'all' ? If I am not mistaken, it also works without 'all'.
madhan ravi
madhan ravi on 3 Apr 2019
Edited: madhan ravi on 3 Apr 2019
all() is appropriate here because we check that each row or column sum equals to total. https://in.mathworks.com/help/matlab/ref/all.html?searchHighlight=All&s_tid=doc_srchtitle - read it
Thank you so much, I learned new things, all() and any() will be very useful.
Regards,

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!