Mean a matrix columnwise based on another logical matrix

3 ビュー (過去 30 日間)
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 6 月 16 日
I want to mean the matrix a based on the logical matrix b columnwise: In other words this:
mean(a(b(:,1)))
mean(a(b(:,2)))
...
a =[
7 8 5 3
1 1 4 7
9 3 8 7
10 1 8 2
7 1 2 2
8 9 5 5
8 7 5 10
4 4 7 4
7 10 8 6
2 1 8 3];
b =logical([
0 0 1 0
1 0 1 0
1 0 1 1
1 0 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
1 0 0 1
0 0 0 1]);
  1 件のコメント
Jan
Jan 2013 年 6 月 18 日
This is obviously an interesting question, which allows to shed light on different powers of Matlab. +1

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

採用された回答

Jan
Jan 2013 年 6 月 16 日
Or:
m = sum(a .* b, 1) ./ sum(b, 1);
  4 件のコメント
Wayne King
Wayne King 2013 年 6 月 17 日
I agree Jan, +1, silly of me not to think of simply using the b matrix to get the correct number of nonzero elements.
Andrei Bobrov
Andrei Bobrov 2013 年 6 月 18 日
+1

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

その他の回答 (4 件)

Andrei Bobrov
Andrei Bobrov 2013 年 6 月 17 日
編集済み: Andrei Bobrov 2013 年 6 月 18 日
b1 = bsxfun(@times,b,1:4);
out = accumarray(b1(b),a(b),[],@mean);
or
[~,jj] = find(b);
out = accumarray(jj,a(b),[],@mean);
and in line with accumarray:
out = accumarray(ceil(find(b)/size(b,1)),a(b),[],@mean);
  2 件のコメント
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 6 月 17 日
I will celebrate the day that I will understand accumarray... Thank you Andrei
Jan
Jan 2013 年 6 月 18 日
Although I do not think that accumarray is the fastest approach here, I vote for it a sign of my admiration for all successful accumarray masters.

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


Wayne King
Wayne King 2013 年 6 月 16 日
編集済み: Wayne King 2013 年 6 月 16 日
you mean just:
mean(a.*b)
or do you want the mean of just the nonzero entries? In other words, divide by the right number of elements.
C = a.*b;
for nn = 1:size(C,2)
numelements(nn) = nnz(C(:,nn));
end
colsumz = sum(C);
meanz = colsumz./numelements;

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 6 月 16 日
c=a.*b
c(c==0)=nan;
out=nanmean(c)
  2 件のコメント
Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 6 月 17 日
Thank you! You had the shortest!
John Doe
John Doe 2013 年 6 月 18 日
Just learned about nanmean. I've been looking for a function like that for quite some time. I've always used some workaround. Thanks!

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


Giorgos Papakonstantinou
Giorgos Papakonstantinou 2013 年 6 月 17 日
Thank you guys!

カテゴリ

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