How to add rows of data in a 5x5 Matrix

Hi, I want to add entries in each row and put zero in the Inf place but I want to use for loop? I tried this
if true
A = sum(A,2);
end
But I am want to put entries equal to Inf to zero and then add them.

 Accepted Answer

If you want to replace the inf values with 0 first, then
A(isinf(A)) = 0;

3 Comments

Given the above matrix if I have to implement this code using for loop is it possible that I can add entries of matrix in this order.
Here tid and rid shows the entry of that column like if rid=1, tid=2 then it mean (1,2) and it will add rest of entries in the row of the above matrix i.e. (1,3)+(1,4)+(1,5).
I have written it as such but I need simple using for loop.
if true
switch(rid)
case 1
if(tid ==2)
sumA(rid,tid) = (A(1,3)+A(1,4)+A(1,5));
end
if(tid ==3)
sumA(rid,tid) =(A(1,2)+A(1,4)+A(1,5));
end
if(tid ==4)
sumA(rid,tid) = (A(1,2)+A(1,3)+A(1,5));
end
if(tid ==5)
sumA(rid,tid) = (A(1,2)+A(1,3)+A(1,4));
end
case 2
if(tid ==1)
sumA(rid,tid)= A(2,3)+A(2,4)+A(2,5);
end
if(tid ==3)
sumA(rid,tid) = A(2,1)+A(2,4)+A(2,5);
end
if(tid ==4)
sumA(rid,tid) = A(2,1)+A(2,3)+A(2,5);
end
if(tid ==5)
sumA(rid,tid) = A(2,1)+A(2,3)+A(2,4);
end
case 3
if(tid ==1)
sumA(rid,tid) = A(3,2)+A(3,4)+A(3,5);
end
if(tid ==2)
sumA(rid,tid) = A(3,1)+A(3,4)+A(3,5);
end
if(tid ==4)
sumA(rid,tid) = A(3,1)+A(3,2)+A(3,5);
end
if(tid ==5)
sumA(rid,tid) = (A(3,1)+A(3,2)+A(3,4));
end
case 4
if(tid ==1)
sumA(rid,tid) = (A(4,2)+A(4,3)+A(4,5));
end
if(tid ==2)
sumA(rid,tid) = (A(4,1)+A(4,3)+A(4,5));
end
if(tid ==3)
sumA(rid,tid) =( A(4,1)+A(4,2)+A(4,5));
end
if(tid ==5)
sumA(rid,tid) =(A(4,1)+A(4,2)+A(4,3));
end
case 5
if(tid ==1)
sumA(rid,tid) = (A(5,2)+A(5,3)+A(5,4));
end
if(tid ==2)
sumA(rid,tid) = (A(5,1)+A(5,3)+A(5,4));
end
if(tid ==3)
sumA(rid,tid) = (A(5,1)+A(5,2)+A(5,4));
end
if(tid ==4)
sumA(rid,tid) = (A(5,1)+A(5,2)+A(5,3));
end
end
end
Wow! You like copy pasting . As soon as you start writing lines of code that only differ according to a pattern, you have to think that the program can do that for you.
The whole of the above code could be replaced by these two lines:
rows = [1, 2, 3, 1, 1]; %row to sum
sumA(rid, tid) = sum(A(rows(rid), setdiff(1:5, [rid tid])));
And if you made a typo and forgot to replace the row number in the case 4 and case 5 (another reason for not copy-pasting redundant code), then it's even simpler:
sumA(rid, tid) = sum(A(rid, setdiff(1:5, [rid tid])));
Thanks alot Guillaume :)
I think in the rows = [1,2,3,4,5] ?? You solved my issue and what if I have to choose a non zero entry of the matrix from a 5x5 matrix. Only one non zero and all zeros and I have to pick that and use for my calculations.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 3 Feb 2016

Commented:

on 3 Feb 2016

Community Treasure Hunt

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

Start Hunting!