How to sum up a few numbers in sequence and save as a separate matrix

2 ビュー (過去 30 日間)
Woonsup Choi
Woonsup Choi 2015 年 12 月 4 日
回答済み: Image Analyst 2015 年 12 月 4 日
I have a matrix like [0; 0; -1; -2; -1; 0; 0; 0; -2; -1; 0]. From here I would like to sum up sequences of non-zero values and save the result in a separate matrix. From the example, the result should be [-4; -3]. How should I write the code?
Thank you.

採用された回答

Jos (10584)
Jos (10584) 2015 年 12 月 4 日
Here is an algorithm:
A = [0; 0; -1; -2; -1; 0; 0; 0; -2; -1; 0] % input
B = cumsum(A)
tf = diff([A==0 ; true])==1
C = B(tf)
D = [C(1) ; diff(C)] % output

その他の回答 (1 件)

Image Analyst
Image Analyst 2015 年 12 月 4 日
An alternate way using the Image Processing Toolbox:
A = [0; 0; -1; -2; -1; 0; 0; 0; -2; -1; 0] % input
measurements = regionprops(logical(A~=0), A, 'Area', 'MeanIntensity');
allAreas = [measurements.Area]
allIntensities = [measurements.MeanIntensity]
integratedValues = allAreas .* allIntensities
Of course you could combine it all into 2 lines if you wanted it more compact (but more cryptic):
measurements = regionprops(logical(A~=0), A, 'Area', 'MeanIntensity');
integratedValues = [measurements.Area] .* [measurements.MeanIntensity]

カテゴリ

Help Center および File ExchangeAnnotations についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by