Help with average of elements in a matrix

3 次查看(过去 30 天)
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 ?

采纳的回答

Andrei Bobrov
Andrei Bobrov 2014-9-10
编辑:Andrei Bobrov 2014-9-10
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,:);

更多回答(2 个)

Iain
Iain 2014-9-10
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 个评论
aurc89
aurc89 2014-9-10
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 2014-9-10
Whoops:
Mnew = squeeze(mean(reshape(M(1:elements_to_use),n,[],size(M,2))));

请先登录,再进行评论。


Image Analyst
Image Analyst 2014-9-10
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.

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by