Gadgou
Gadgou

Reputation: 3

Shrink matrix to certain size

I'm very new to MatLab. I'm working with huge matrices made by a sensor, so I'll be using smaller ones as examples for my question.

Suppose I have these 2 matrices

matrix 1

  1 1 1 1 1 1 0 0 6 0 0 0
  0 1 1 1 1 0 0 0 0 4 0 0
  1 1 1 1 1 1 0 0 3 3 0 0
  0 2 2 6 0 1 3 1 2 1 1 3
  0 0 2 6 0 1 2 1 2 1 1 2
  0 2 4 0 1 0 0 2 2 1 2 0

matrix 2

  0 2 1 4 0 0 0 1 1 3 2 0
  0 2 1 2 5 0 1 2 3 3 1 0
  0 1 2 3 0 0 0 1 2 2 0 0
  2 2 2 2 0 1 0 3 2 2 2 0
  2 2 2 4 0 2 3 1 2 2 2 2
  2 2 2 4 0 2 0 3 2 2 3 2
  3 2 1 5 0 1 0 1 3 3 4 1
  0 3 1 6 0 1 1 2 3 2 2 1
  0 2 1 4 0 1 1 2 3 2 0 0

I would like to resize them into 2 matrices with the same size (say, 4 lines each) without losing the average values, so if we had an 8 line matrix, it would have to remove every other line and not the first or last 4 lines.

Can anyone help me out?

Upvotes: 0

Views: 8860

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112679

No need to use imresize (which is part of the Image Processing Toolbox). You can average every n rows by just playing a bit with dimensions and using mean:

result = squeeze(mean(reshape(permute(matrix,[1 3 2]),n,[],size(matrix,2))))

For example:

matrix = [ 1     1     1     1     1     1     0     0
           0     1     1     1     1     0     0     0
           1     1     1     1     1     1     0     0
           0     2     2     6     0     1     3     1
           0     0     2     6     0     1     2     1
           0     2     4     0     1     0     0     2 ];
n = 2;

give

result =

    0.5000    1.0000    1.0000    1.0000    1.0000    0.5000         0         0
    0.5000    1.5000    1.5000    3.5000    0.5000    1.0000    1.5000    0.5000
         0    1.0000    3.0000    3.0000    0.5000    0.5000    1.0000    1.5000

Upvotes: 2

Daniel
Daniel

Reputation: 36710

To remove every other row, you may use:

M(1:2:end,:)=[]

This does not maintain the average in all cases, the already mentioned imresize might be an option.

Upvotes: 1

Related Questions