开发者

Inserting rows into matrix matlab

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.


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]);


%# 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;


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜