フィルターのクリア

how to find the sum of multiple non zero elements in an array

2 ビュー (過去 30 日間)
Mitson Monteiro
Mitson Monteiro 2013 年 6 月 4 日
hi, i have an array that has like zero and non zero elements like eg: 0 0 0 1 1 1 0 0 0 3 3 3 0 0 0
so i want output i=3 and j=9 that is the sum of first set on nonzero elements seporate and the second seporate
  1 件のコメント
Jan
Jan 2013 年 6 月 4 日
Is "i" and "j" really required? Note that this might get extremely complicated, when you have 5000 such blocks and have to avoid collisions with other existing variables.

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

採用された回答

Jan
Jan 2013 年 6 月 4 日
編集済み: Jan 2013 年 6 月 4 日
a = [0 0 0 1 1 1 0 0 0 3 3 3 0 0 0];
c = cumsum(a);
index = strfind([a,0] ~= 0, [true, false]);
result = [c(index(1)), diff(c(index))];
Not tested yet!
  2 件のコメント
Mitson Monteiro
Mitson Monteiro 2013 年 6 月 5 日
thanks buddy, for ur answers.... what if i want the index values of the non zero numbers so that i can minus the first index from the last index of first set and the second set and if there are more than one colum data
Jan
Jan 2013 年 6 月 5 日
@Mitson: Do you mean something like this:
index = strfind([0, a] ~= 0, [false, true]) + 1;

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

その他の回答 (3 件)

Roger Stafford
Roger Stafford 2013 年 6 月 4 日
There is an ambiguity in the posing of this problem. Are the sets of nonzero numbers distinguished from one another by their values or by their contiguity? For example, if your vector were [1 3 0 3 1] do you want [2 6] (distinguished by values) as a result or [4 4] (distinguished by contiguity)? The following assumes the latter.
Let x be the row vector of your numbers.
t = [0,x,0];
c = cumsum(t);
f = find(diff(t~=0)~=0);
r = c(f(2:2:end))-c(f(1:2:end));
My apologies to you, Jan, if this seems too similar to your solution. I couldn't resist giving it.
  3 件のコメント
Roger Stafford
Roger Stafford 2013 年 6 月 4 日
編集済み: Roger Stafford 2013 年 6 月 4 日
Don't you mean the former, Matt?
Matt J
Matt J 2013 年 6 月 4 日
Um. Yes, the former.

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


Matt J
Matt J 2013 年 6 月 4 日
[u,i,j]=unique([0 0 0 1 1 1 0 0 0 3 3 3 0 0 0])
result = histc(j,1:max(j)).*u

Mitson Monteiro
Mitson Monteiro 2013 年 6 月 5 日
thanks buddy, for ur answers.... what if i want the index values of the non zero numbers so that i can minus the first index from the last index of first set and the second set and if there are more than one colum data

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by