Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab adding rows and columns elegantly

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'd like to transform it into 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 cannot use mathjax format so it looks a bit awful, sorry for this. Point, is, that I want to add row and columns of zeros in between of my current rows and columns so that I increase its size 2x.

I came up with the following code, but it only works for very small matrixes if i use it on a a big image it cannot finish due to memory limitation problems.

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 fully vectorised with maltlab functions but it fails miserably. Is there some other elegant way to do this?

like image 222
Jimodium Avatar asked Sep 26 '22 06:09

Jimodium


2 Answers

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

like image 158
Daniel Avatar answered Sep 29 '22 16:09

Daniel


This can be also done via the one liner, say your original matrix is called A, then

kron(A,[1,0;0,0])
like image 23
percusse Avatar answered Sep 29 '22 17:09

percusse