tags:

views:

105

answers:

3

I have a ~ 100000/2 matrix. I'd like to go down the columns, average each vertically adjacent value, and insert that value in between the two values. For example...

1  2
3  4
4  6
7  8

would become

1   2
2   3
3   4
3.5 5
4   6
5.5 7
7   8

I'm not sure if there is a terse way to do this in matlab. I took a look at http://www.mathworks.com/matlabcentral/fileexchange/9984 but it seems to insert all of the rows in a matrix into the other one at a specific point. Obviously it can still be used, but just wondering if there is a simpler way.

Any help is appreciated, thanks.

+1  A: 

Untested:

% Take the mean of adjacent pairs
x_mean = ([x; 0 0] + [0 0; x]) / 2;
% Interleave the two matrices
y = kron(x, [1;0]) + kron(x_mean(1:end-1,:), [0;1]);
Oli Charlesworth
You need parenthesis around [x; 1 0] + [1 0; x].
gary comtois
Fixed it, thanks!
Oli Charlesworth
The only issue here is that it includes values before and after the first and last values in the column, respectively. Edit: That did it! Thanks!
random
A: 
octave-3.0.3:57> a = [1,2; 3,4; 4,6; 7,8]
a =

   1   2
   3   4
   4   6
   7   8

octave-3.0.3:58> b = (circshift(a, -1) + a) / 2
b =

   2.0000   3.0000
   3.5000   5.0000
   5.5000   7.0000
   4.0000   5.0000

octave-3.0.3:60> reshape(vertcat(a', b'), 2, [])'(1:end-1, :)
ans =

   1.0000   2.0000
   2.0000   3.0000
   3.0000   4.0000
   3.5000   5.0000
   4.0000   6.0000
   5.5000   7.0000
   7.0000   8.0000
KennyTM
+1  A: 
%# works for any 2D matrix of size N-by-M
X = rand(100,2);

adjMean = mean(cat(3, X(1:end-1,:), X(2:end,:)), 3);

Y = zeros(2*size(X,1)-1, size(X,2));
Y(1:2:end,:) = X;
Y(2:2:end,:) = adjMean;
Amro

related questions