Help with average of elements in a matrix
조회 수: 1 (최근 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 ?
댓글 수: 0
채택된 답변
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,:);
댓글 수: 0
추가 답변 (2개)
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
Iain
2014년 9월 10일
Whoops:
Mnew = squeeze(mean(reshape(M(1:elements_to_use),n,[],size(M,2))));
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!