Adding zeros between every 2 matrix elements in matlab / octave

I am wondering how to add rows and columns of zeros to a matrix so that it looks like this:

              1 0 2 0 3
1 2 3         0 0 0 0 0
2 3 4  =>     2 0 3 0 4
5 4 3         0 0 0 0 0
              5 0 4 0 3

Actually, Iโ€™m interested in how I can do this effectively, because walking around the matrix and adding zeros takes a lot of time if you are working with a large matrix.

Update:

Many thanks.

Now I'm trying to replace zeros with the sum of my neighbors:

              1 0 2 0 3     1 3 2 5 3
1 2 3         0 0 0 0 0     3 8 5 12... and so on
2 3 4  =>     2 0 3 0 4 =>
5 4 3         0 0 0 0 0
              5 0 4 0 3

as you can see, I consider all 8 neighbors of the element, but again, using the matrix for and walking, it slows me down a bit, is there a faster way?

+3
source share
2 answers

Let your little matrix be called m1. Then:

m2 = zeros(5)

m2(1:2:end,1:2:end) = m1(:,:)

Obviously, it is difficult to connect to your example, I will leave it to generalize.

+3

2 . , conv2. .

M=[1 2 3; 2 3 4 ; 5 4 3];

% this matrix (M expanded) has zeros inserted, but also an extra row and column of zeros
Mex = kron(M,[1 0 ; 0 0 ]); 

% The sum matrix is built from shifts of the original matrix
Msum = Mex + circshift(Mex,[1 0]) + ...
             circshift(Mex,[-1 0]) +...
             circshift(Mex,[0 -1]) + ...
             circshift(Mex,[0 1]) + ...
             circshift(Mex,[1 1]) + ...
             circshift(Mex,[-1 1]) + ...
             circshift(Mex,[1 -1]) + ...
             circshift(Mex,[-1 -1]);

% trim the extra line
Msum = Msum(1:end-1,1:end-1)


% another version, a bit more fancy:
MexTrimmed = Mex(1:end-1,1:end-1);
MsumV2 = conv2(MexTrimmed,ones(3),'same')

:

Msum =

1    3    2    5    3
3    8    5   12    7
2    5    3    7    4
7   14    7   14    7
5    9    4    7    3

MsumV2 =

1    3    2    5    3
3    8    5   12    7
2    5    3    7    4
7   14    7   14    7
5    9    4    7    3
0

All Articles