Adding rows with constraint

2 views (last 30 days)
Bathrinath
Bathrinath on 9 Jan 2014
Answered: David Sanchez on 9 Jan 2014
a=[10,11,8; 6,5,7; 4,6,5; 0,0,5]; output=[10,11,8; 16,16,15; 20,22,20; 0,0,25];
First row should be as it is, in the second row elements should be added, in the third row also elements should be added but in the final row if '0' is there that column should not be added column with out '0' has to be added.

Accepted Answer

dpb
dpb on 9 Jan 2014
b=cumsum(a);
b(a==0)=0;

More Answers (1)

David Sanchez
David Sanchez on 9 Jan 2014
a=[
10,11,8;
6,5,7;
4,6,5;
0,0,5];
output = zeros(size(a));
output(1,:) = a(1,:);% First row should be as it is
output(2,:) = sum(a(1:2,:),1); % the second row elements should be added
output(3,:) = sum(a(1:3,:),1);
output(4,:) = sum(a(1:4,:),1).*(a(4,:)~=0);% final row if '0' is there that column should not be added column with out '0' has to be added.
>> output
output =
10 11 8
16 16 15
20 22 20
0 0 25

Categories

Find more on Mathematics 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!