Mean of matrix subarrays without using a loop.

2 ビュー (過去 30 日間)
Santos García Rosado
Santos García Rosado 2021 年 3 月 16 日
Hi Mathworks community.
I'm trying to calculate the mean value of my matrix subarrays without taking the zero values into account. I know how to do it using a loop, but in this case I'd like to avoid it.
The code should take matrix A:
A = [1 0 3 5 0 7; 0 2 6 0 8 0; 3 5 0 0 2 0]
And calculate the mean value of the subarray for each row in steps of 3. So the output should look like:
Out = [2 6; 4 8; 4 2]
I'm trying to improve this code, since I'll be working with much bigger matrixes and I won't be able to do it manually:
Out = mean(nonzeros(A(1,1:3)));
Any help would be much appreciated.
Thanks in advance,
Santos

採用された回答

Stephen23
Stephen23 2021 年 3 月 16 日
編集済み: Stephen23 2021 年 3 月 16 日
A = [1 0 3 5 0 7; 0 2 6 0 8 0; 3 5 0 0 2 0]
A = 3×6
1 0 3 5 0 7 0 2 6 0 8 0 3 5 0 0 2 0
B = reshape(A.',3,[]);
B(B==0) = NaN;
C = reshape(mean(B,1,'omitnan'),[],size(A,1)).'
C = 3×2
2 6 4 8 4 2
Or
F = @(s)mean(nonzeros(s.data));
C = blockproc(A,[1,3],F) % requires the Image Toolbox.
C = 3×2
2 6 4 8 4 2
  1 件のコメント
Santos García Rosado
Santos García Rosado 2021 年 3 月 16 日
Nice and clean code. Thank you Stephen!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by