Higashi Yutaka
Higashi Yutaka

Reputation: 181

Mean values of a matrix in a matrix on Matlab

This is about matlab. Let's say I have a matrix like this

A = [1,2,3,4,5;6,7,8,9,10;11,12,13,14,15]‍

Now I want to know how to get a mean value of a small matrix in A. Like a mean of the matrix located upper left side [1,2;6,7]

The only way I could think of is cut out the part I want to get a value from like this

X = A(1:2,:);
XY = X(:,1:2);

and mean the values column wise Mcol = mean(XY);.

and finally get a mean of the part by meaning Mcol row-wise.

Mrow = mean(Mcol,2);

I don't think this is a smart way to do this so it would be great if someone helps me make it smarter and faster.

Upvotes: 1

Views: 160

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

Your procedure is correct. Some small improvements are:

  • Get XY using indexing in a single step: XY = A(1:2, 1:2)
  • Replace the two calls to mean by a single one on the linearized submatrix: mean(XY(:)).
  • Avoid creating XY. In this case you can linearize using reshape as follows: mean(reshape(A(1:2, 1:2), 1, [])).

If you want to do this for all overlapping submatrices, im2col from the Image Processing Toolbox may be handy:

submatrix_size = [2 2];
A_sub = im2col(A, submatrix_size);

gives

A_sub =
     1     6     2     7     3     8     4     9
     6    11     7    12     8    13     9    14
     2     7     3     8     4     9     5    10
     7    12     8    13     9    14    10    15

that is, each column is one of the submatrices linearized. So now you only need mean(A_sub, 1) to get the means of all submatrices.

Upvotes: 2

Related Questions