How to average a multidimensional array with surroundings
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello
Say I have a 3x3 array. I want to average the values dim1 and dim2 so that the center value is the average of the center value, value above and below, and value left and right, but not the values diagonal. The same applies for all values, except in the case of the edges, the mirror values should be used: for example, on the left side, the right values are the center column, and the left side values should also be the center column because a mirror image is imposed. The same should apply for the above and below values. To clarify, when no value for averaging is present, use the mirror value.
So for example, on value (1,1), the average would be (1,1), 2 * (1,2), and 2 * (2,1) because the left and top values have to be mirror values. The center value (2,2) is the average of (2,2), (1,2), (2,1), (2,3), (3,2). Hope this clarifies the issue.
Now, take this concept and use it on 5 x 4 arrays. And now take it even further and use it on multidimensional arrays like 10 x 9 x 8, or 120 x 200 x 300 x 5.
Is there an easy algorithm for this?
Thank you
0 comentarios
Respuestas (2)
Andrei Bobrov
el 14 de Mzo. de 2013
Editada: Andrei Bobrov
el 14 de Mzo. de 2013
k = reshape(1:9,3,[]) % your array
k1 = [k(:,2),k,k(:,end-1)];
k1 = [k1(2,:);k1;k1(end-1,:)]
out = conv2(k1,[0 1 0;1 1 1;0 1 0]*.2,'valid')
for 3-D arrays use convn
0 comentarios
Teja Muppirala
el 14 de Mzo. de 2013
Editada: Teja Muppirala
el 14 de Mzo. de 2013
This would be much simpler if it were not for that weird edge case. Anyways, this is how you would do it in the case of an arbitrary sized matrix:
A = rand(3,4,5,6); %<-- Your input matrix of any size
d=ndims(A);
C = cell(1,d);
[C{:}] = ndgrid([1 0 1]);
K = sum(cat(d+1,C{:}),d+1) <= 1;
K = K/nnz(K); %<-- Get the convolution kernel
% Reflect the edges for each dimension
Ac = A;
for n = 1:d
sz = size(A,n);
edge1 = [repmat({':'},1,n-1) {2} repmat({':'},1,d-n)];
edge2 = [repmat({':'},1,n-1) {sz-1} repmat({':'},1,d-n)];
Ac = cat(n,Ac(edge1{:}), Ac, Ac(edge2{:}));
end
% Do the calculation
B = convn(Ac,K,'valid') %<-- Your answer
clear('Ac'); %<-- Don't need this anymore
3 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices 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!