How can i make the sum of matrix elements>0 under the condition that there are min 3 zeros between the sums?

I hava a matrix: a=[2 3 0 0 4; 0 0 0 0 0; 0 5 3 0 4; 14 4 0 1 1; 0 0 0 0 0; 0 0 0 7 9; 0 0 0 0 0; 0 0 0 0 0; 9 6 0 0 1; 1 1 1 0 0];
How can i make the sum of elements>3, under the condition that there are at least 3 zeros between the last element of one and the first element of the next sum?
Output should be: E=[9 32 16 19]
thanks!

 Accepted Answer

a=[2 3 0 0 4; 0 0 0 0 0; 0 5 3 0 4; 14 4 0 1 1; 0 0 0 0 0; 0 0 0 7 9; 0 0 0 0 0; 0 0 0 0 0; 9 6 0 0 1; 1 1 1 0 0]
b=reshape(a',1,[]);
id=~b;
ii=strfind(id,[1 1 1 0])+2;
ii=[0 ii numel(b)];
for k=1:numel(ii)-1
out(k)=sum(b(ii(k)+1:ii(k+1)));
end
out

10 Comments

Thank you very much for your help! it works perfectly! is there any way to pick out the row in the matrix where a sum started? in our example: [1 3 6 9]
Now I want to work with larger matrix and have to extend the condition from 3 to 36 zeros between sums. I edited it with:
b=reshape(a',1,[]);
id=~b;
ii=strfind(id,[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0])+2;
ii=[0 ii numel(b)];
for k=1:numel(ii)-1
out(k)=sum(b(ii(k)+1:ii(k+1)));
end
[~,idx]=ind2sub(size(NMatrix'),ii(1:end-1)+1);
it seems to work for the sums but not for the rows. can u please check the edited code? thanks
If you change the criterion 3 zeros to 36, you need to change the code
n=36
ii=strfind(id,[ones(1,n) 0])+n-1;
Thanks! one last thing: is there any way to get the number of elements(inclusive zeros) in each sum? in the example above:
sum1=9 ->5
sum2=32 ->9
sum3= 16 ->2
sum4=19 ->8
i would like to apply this for my large matrix with the condition of 36 zeros for sums. thanks!
Yes, but first we need to know how you got those numbers. For example, assuming the sums are row sums, the first row is [2 3 0 0 4], which sums to 9. There are 2 regions, and 3 elements (2 (a 2 and a 3) in region 1 and 1 (a 4) in region 2). So how do you get a 5?
the sum1=9 consists of 5 elements: 2+3+0+0+4. i count the zeros between the regions as elemnts as well. to be more precise, i am looking for the number of elements between first and last summand in a sum.
Then you simply want the number of columns in the matrix:
[rows, columns] = size(yourMatrix);
In your example, columns will be 5.
but the sums are not row sums. this was just an assumption you've done in the comment above.
is there any way to get the number of elements in a sum? maybe somehow with the difference between the end position and beginning position of the sum? in our example for sum 9=2+3+0+0+4, there are 5 summands

Sign in to comment.

More Answers (0)

Asked:

on 23 Apr 2016

Commented:

on 4 May 2016

Community Treasure Hunt

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

Start Hunting!