Summing few sequences in a vector

2 ビュー (過去 30 日間)
George Tsintsadze
George Tsintsadze 2016 年 12 月 20 日
コメント済み: Walter Roberson 2016 年 12 月 20 日
How can I sum few sequences in a vector? For example, if I have the vector:
A = [1 1 0 4 1 1 0 2 1 1 1]
I want to get the vector:
B = [2 6 5]
Which is the sum of sequences separated by zero.
Of curse I wand to do it without any for/while loops.
Thank you.

採用された回答

Walter Roberson
Walter Roberson 2016 年 12 月 20 日
t1 = cumsum(A);
B = diff([0,t1(A==0),B(end)]);
  2 件のコメント
George Tsintsadze
George Tsintsadze 2016 年 12 月 20 日
You can't execute the second line because B is not defined before it and you are using it in this line.
I tried your code and got the warning:
Undefined function or variable 'B'.
Do you have a suggestion how to fix it?
Walter Roberson
Walter Roberson 2016 年 12 月 20 日
t1 = cumsum(A);
B = diff([0,t1(A==0),t1(end)]);

サインインしてコメントする。

その他の回答 (2 件)

KSSV
KSSV 2016 年 12 月 20 日
編集済み: KSSV 2016 年 12 月 20 日
A = [1 1 0 4 1 1 0 2 1 1 1] ;
ne0 = find(A~=0); % Nonzero Elements
i0 = unique([ne0(1) ne0(diff([0 ne0])>1)]); % Segment Start Indices
i1 = ne0([find(diff([0 ne0])>1)-1 length(ne0)]); % Segment End Indices
for k1 = 1:length(i0)
section{k1} = A(i0(k1):i1(k1));
end
iwant = cellfun(@sum,section)
  1 件のコメント
George Tsintsadze
George Tsintsadze 2016 年 12 月 20 日
Sorry but I asked for solutions without any for/while loops...

サインインしてコメントする。


José-Luis
José-Luis 2016 年 12 月 20 日
Not particularly efficient but fulfilling the eternal quest for one liners:
result = cellfun(@(x) sum(x((x - '0') > 0 & (x - '0') <= 9 ) - '0'), strsplit(num2str(A),'0'))
  2 件のコメント
George Tsintsadze
George Tsintsadze 2016 年 12 月 20 日
Why did you add the condition
(x - '0') <= 9
in the logical indexing of x?
José-Luis
José-Luis 2016 年 12 月 20 日
Because
strsplit(num2str(A),'0')
returns a cell array of character arrays and I wanted to perform the comparisons on numbers. It's just a way of transitioning from characters to numbers. Otherwise some unnecessary blank characters would have been included in the computation.
Please accept the answer that best solves your problem.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by