Matlab elegantly adds rows and columns

Let's say that we have the following random matrix:

1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 

I would like to convert it to the following:

 1 0 2 0 3 0 4 0 0 0 0 0 0 0 0 0 5 0 6 0 7 0 8 0 0 0 0 0 0 0 0 0 9 0 8 0 7 0 6 0 0 0 0 0 0 0 0 0 5 0 4 0 3 0 2 0 0 0 0 0 0 0 0 0 

For some reason I can't use the mathjax format, so it looks a little awful, sorry for that. The point is that I want to add rows and columns of zeros between my current rows and columns in order to increase its size 2x.

I came up with the following code, but it only works for very small matrices, if I use it on a large image, which it cannot complete due to memory limitations.

 clear all I=imread('image.png'); I=rgb2gray(I); B=zeros(2*size(I)); [x, y]=find(-inf<I<inf); xy=[x,y]; nxy=xy; %coord change nxy=2*xy-1; B(nxy(:,1),nxy(:,2))=I(xy(:,1),xy(:,2)); 

I expected to be fast because it is completely vector with maltlab functions, but it fails. Is there any other elegant way to do this?

+5
source share
2 answers

If you look at your indexing vectors, this is something like I([1 1 2 2] ,[1 2 1 2] ); for a 2x2 matrix, which means that you index each row and column twice. The correct solution is B(1:2:end,1:2:end)=I; which indexes every second row and every second column.

+3
source

This can also be done with a single insert, let's say your original matrix is ​​called A , then

 kron(A,[1,0;0,0]) 
+1
source

Source: https://habr.com/ru/post/1244028/


All Articles