How do I sum the first 3 values after each zero
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2018-5-17
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.
采纳的回答
per isakson
2018-5-17
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
更多回答(1 个)
Image Analyst
2018-5-17
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 个评论
Image Analyst
2018-5-17
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?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!