How do I sum the first 3 values after each zero
古いコメントを表示
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.
Chris Matthews
2018 年 5 月 17 日
採用された回答
その他の回答 (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 件のコメント
Chris Matthews
2018 年 5 月 17 日
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?
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!