Sum of nonzero vector elements

42 ビュー (過去 30 日間)
hdiba
hdiba 2016 年 9 月 15 日
コメント済み: hdiba 2016 年 9 月 15 日
Hallo everybody!
i have a vector with zeros and nonzero-entries. Now i would like to make the sum of the nonzero-elements between the zeros.example:
v= 1 2 3 0 0 0 4 5 0 6 7 0 8 9
out=6 9 13 17
in addition i would like to know the number of elements in each sum and the index of the first-sum element.
num= 3 2 2 2
indx= 1 7 10 13
can anyone help? thanks
  1 件のコメント
José-Luis
José-Luis 2016 年 9 月 15 日
Is this homework? What have you tried so far?
You could have a look at bwconncomp().

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

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 9 月 15 日
v= [1 2 3 0 0 0 4 5 0 6 7 0 8 9]
ii=[0 v~=0 0]
idx1=strfind(ii,[0 1])
idx2=strfind(ii,[1 0])-1
out=cell2mat(arrayfun(@(x,y) [sum(v(x:y));y-x+1;x],idx1,idx2,'un',0))
  1 件のコメント
hdiba
hdiba 2016 年 9 月 15 日
Thanks a lot !! perfect

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

その他の回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2016 年 9 月 15 日
編集済み: Andrei Bobrov 2016 年 9 月 15 日
v= [1 2 3 0 0 0 4 5 0 6 7 0 8 9];
b = bwlabel(v(:));
[a,ii] = unique(b,'first');
indx = ii(a ~= 0);
t = b ~= 0;
num = accumarray(b(t),1);
out = accumarray(b(t),v(t));
if you not have Image Processing Toolbox then:
t = v(:) ~= 0;
p = diff([false;t]) == 1;
indx2 = find(p);
ii = cumsum(p);
num2 = accumarray(ii,t);
out2 = accumarray(ii,v(:));

カテゴリ

Find more on Creating and Concatenating Matrices 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!

Translated by