4

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.

3 Answers 3

2

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

You need parenthesis around [x; 1 0] + [1 0; x].
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!
1
%# 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;

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.