How do I sum the first 3 values after each zero
4 views (last 30 days)
Show older comments
Chris Matthews
on 16 May 2018
Commented: Image Analyst
on 17 May 2018
Hi all, I have matrix X, and want to sum the first 3 values after each zero. So far I've managed to sum each block of values after a zero, but I need to modify this to output only the first 3 values after a zero.
clear all
clc
x=[0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
t = [0,x,0];
c = cumsum(t);
f = find(diff(t~=0)~=0);
r = c(f(2:2:end))-c(f(1:2:end));
%output is r = [15,34,10,2];
%but i want r = [7, 19, 10, 2];
Thanks guys!
2 Comments
Image Analyst
on 17 May 2018
It looks like you want the sum of the first 3 values not after EACH zero, but after the LAST zero in a run of zeros. Because the first zero is at index 1 and the sum of the first 3 numbers after that (at indexes 2, 3, and 4) is 3, not 7.
Accepted Answer
per isakson
on 17 May 2018
This
x = [0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
dx = [ 0, diff( x ) ];
len = length( x );
is0 = [ false, ( x == 0 ) ];
is0(end) = [];
ix_start = find( is0 & not(dx==0) );
out = nan( size( ix_start ) );
for jj = 1 : length( ix_start )
out(jj) = sum( x( ix_start(jj) : min( ix_start(jj)+2, len ) ) );
end
outputs
>> disp( out )
7 19 10 2
More Answers (1)
Image Analyst
on 17 May 2018
Here is another way that works, if you have the Image Processing Toolbox.
x = [0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
% Get values after the last zero in each run of zeros.
props = regionprops(x~=0, x, 'PixelValues');
% Determine the "r" array:
for k = 1 : length(props)
theseValues = props(k).PixelValues; % Extract all values after the zero.
lastIndex = min(length(theseValues), 3); % Determine how many to sum up.
r(k) = sum(theseValues(1:lastIndex)) % Do the sum.
end
2 Comments
Image Analyst
on 17 May 2018
Just do it twice:
x = [0 0 1 2 4 2 5 1 0 0 3 7 9 6 9 0 0 0 0 3 7 0 0 0 2];
differences = [0, diff(x)]
% Get values after the last zero in each run of zeros.
props = regionprops(x~=0, x, 'PixelValues');
propsDiff = regionprops(x~=0, differences, 'PixelValues');
% Determine the "r" array:
for k = 1 : length(props)
theseValues = props(k).PixelValues; % Extract all values after the zero.
lastIndex = min(length(theseValues), 3); % Determine how many to sum up.
r(k) = sum(theseValues(1:lastIndex)); % Do the sum.
% Do the same for the differences.
theseValues = propsDiff(k).PixelValues; % Extract all values after the zero.
rDiff(k) = sum(theseValues(1:lastIndex)); % Do the sum.
end
r
rDiff
If it works, could you Vote for my answer?
See Also
Categories
Find more on Logical 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!