Help with average of elements in a matrix

1 visualización (últimos 30 días)
aurc89
aurc89 el 10 de Sept. de 2014
Respondida: Image Analyst el 10 de Sept. de 2014
I have a matrix M with dimension 630x500. I want to do an average of its values along vertical direction, in order to have a matrix with smaller dimension. For example, I want to obtain a matrix with dimension 210x500: this means that, every three values along each column, I take just one (which is the average of the three values). I do this with the following code:
n=3
M = squeeze(mean(reshape(M,n,[],size(M,2))));
Let's suppose that, instead of three, I want to do an average over four values, i.e. I take just one value which is the average of the four values. This line
n=4
M = squeeze(mean(reshape(M,n,[],size(M,2))));
doesn't work, because I cannot divide 630 by four ! How can I find a way to approximate best this requirement ? For example, I can do an average over the first 628 elements (628 contains 4) and let the last two elements unchanged. How can I do this automatically once I have chosen an integer n ?

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 10 de Sept. de 2014
Editada: Andrei Bobrov el 10 de Sept. de 2014
n = 3;
s = size(M);
out = squeeze(nanmean(reshape([M;nan(mod(-s(1),n),s(2))],n,[],s(2))));
without nanmean :
s = size(M);
n = 3;
k = rem(s(1),n);
M1 = [M;zeros(n-k,s(2))];
out = squeeze(bsxfun(@rdivide,...
sum(reshape(M1,n,[],s(2))),[repmat(n,1,floor(s(1)/n)),k]));
other variant
M2 = conv2(M,[1;1;1]/3);
out = M2(n:n:end,:);

Más respuestas (2)

Iain
Iain el 10 de Sept. de 2014
n=4
elements = numel(M);
sets = round( elements / n / size(M,2));
elements_to_use = sets * n * size(M,2);
Mnew = squeeze(mean(reshape(M(1:round(numel(M(1:elements))/(n*size(M,2)) ) ,n,[],size(M,2))));
Mnew(:,(end+1):(end+elements - elements_to_use)) = M((elements_to_use+1):end);
  2 comentarios
aurc89
aurc89 el 10 de Sept. de 2014
It gives me this error:
Index exceeds matrix dimensions.
for the line
Mnew = squeeze(mean(reshape(M(1:round(numel(M(1:elements))/(n*size(M,2)) ) ,n,[],size(M,2))));
whatever is n
Iain
Iain el 10 de Sept. de 2014
Whoops:
Mnew = squeeze(mean(reshape(M(1:elements_to_use),n,[],size(M,2))));

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 10 de Sept. de 2014
If you have the Image Processing Toolbox, simply do
resizedMatrix = imresize(M, [230, 500]);
There are a variety of averaging and interpolation techniques you can choose from as third input arguments.

Categorías

Más información sobre Numeric Types en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by