필터 지우기
필터 지우기

Help with average of elements in a matrix

조회 수: 1 (최근 30일)
aurc89
aurc89 2014년 9월 10일
답변: Image Analyst 2014년 9월 10일
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에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by