find sum of the run length of non zero elements between zeros of a matrix

3 vues (au cours des 30 derniers jours)
suppose my matrix is
a=[ 1 2 3 0 0 0 4 5 6 0 0 0 7 8 0 0 9 0 0 ]
output wanted is
[6 15 15 9]

Réponse acceptée

Walter Roberson
Walter Roberson le 10 Juil 2021
a = [ 1 2 3 0 0 0 4 5 6 0 0 0 7 8 0 0 9 0 0 ]
a = 1×19
1 2 3 0 0 0 4 5 6 0 0 0 7 8 0 0 9 0 0
mask = logical(a);
starts = strfind([0 mask], [0 1]);
stops = strfind([mask 0], [1 0]) + 1;
ca = cumsum([0 a]);
ca(stops) - ca(starts)
ans = 1×4
6 15 15 9

Plus de réponses (4)

Soniya Jain
Soniya Jain le 10 Juil 2021
a=[ 1 2 3 0 0 0 4 5 6 0 0 0 7 8 0 0 9 0 0 ];
j = 0;
i = 1;
while i ~= (length(a)+1)
if a(i)~=0
sum = 0;
while a(i)~=0
sum = sum + a(i);
i = i + 1;
end
j = j + 1;
res(j) = sum;
end
i = i + 1;
end
Here is the code of it, but if you are not familiar with how to write MATLAB code, then you can start with the MATLAB Onramp tutorial to quickly learn the essentials of MATLAB.
  2 commentaires
PRIYAM DEKA
PRIYAM DEKA le 10 Juil 2021
this code works but if the last element is non zero the code doesnot work.
though it can be corrected by defining a=[a 0] before the while loop.
thank you
Soniya Jain
Soniya Jain le 11 Juil 2021
Oh yes, thanks for noticing that!

Connectez-vous pour commenter.


Simon Chan
Simon Chan le 10 Juil 2021
a=[ 1 2 3 0 0 0 4 5 6 0 0 0 7 8 0 0 9 0 0 ];
pos=diff(a)<0; % Position before hitting a zero
c=cumsum(a); % Cumulative sum
d=[0 c(pos)]; % Add a zero in the first position, otherwise first value will be lost
diff(d)

Matt J
Matt J le 10 Juil 2021
Modifié(e) : Matt J le 10 Juil 2021
Using this File Exchange submission
it is quite easy.
result=groupFcn(@sum, a, groupTrue(a~=0))

Image Analyst
Image Analyst le 11 Juil 2021
Here's another way:
a = [ 1 2 3 0 0 0 4 5 6 0 0 0 7 8 0 0 9 0 0 ]
% Extract each run:
props = regionprops(logical(a), a, 'PixelValues')
% Sum up each run.
for k = 1 : length(props)
theSums(k) = sum(props(k).PixelValues)
end

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by