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!