フィルターのクリア

Sum elements in matrix if equal to value in another element

1 回表示 (過去 30 日間)
Christopher
Christopher 2014 年 10 月 7 日
回答済み: Thorsten 2014 年 10 月 7 日
I have the matrix OVEC, which consists of a number of column vectors with numbers
How do I sum all the elements in each column between row 2 and end if their values are the same as the value in row 1? The procedure should return a row vector of width size(OVEC(1,:))
So if
OVEC = [ 1 2 3 4 5 6
1 1 1 1 1 1
1 6 4 5 5 5
4 4 4 4 4 3];
then I should return the row vector [2, 0, 0, 1, 0]
I tried:
Osumvec = sum(ovec(2:end)==ovec(1,:),1)
But my code is erroneous.
  3 件のコメント
Stephen23
Stephen23 2014 年 10 月 7 日
編集済み: Stephen23 2014 年 10 月 7 日
OVEC has six columns, but your example output vector only has five. Is [2,0,0,1,1,0] the correct output? (I.e. the count of elements matching the first row?)
Christopher
Christopher 2014 年 10 月 7 日
編集済み: Christopher 2014 年 10 月 7 日
yes sorry, you are right Stephen.
Adam, I need a count, but I can probably turn a sum into a count by division.
I need a fast vectorized operation for this.

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

回答 (2 件)

Stephen23
Stephen23 2014 年 10 月 7 日
編集済み: Stephen23 2014 年 10 月 7 日
If you want the count:
idx = bsxfun(@eq,OVEC,OVEC(1,:));
sum(idx,1)-1
If you want the sum:
idx(1,:) = false;
sum(OVEC.*idx,1)

Thorsten
Thorsten 2014 年 10 月 7 日
To sum the elements
for i=1:size(ovec, 2)
r(i) = sum(ovec(find(ovec(2:end,i)==ovec(1,i))+1, i));
end
To count the elements
for i=1:size(ovec, 2)
r(i) = sum(ovec(2:end,i)==ovec(1,i));
end

カテゴリ

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