tags:

views:

50

answers:

2

Let's say I've got a vector a = [1 2 4]. I want it converted into a vector which looks like this b = [1 2 0 4], i.e. each number is placed into a correct position and since 3 is not included into the vector a, it is replaced by 0 in vector b. This can be done the following way:

a = [1 2 4]
b = zeros(1, size(a, 2));
b(1, a) = a;

I can't figure out a way to do the same for a matrix. For example,

c = [1 4 2 0; 3 1 0 0; 4 0 0 0; 1 3 4 0];

I need to convert into a matrix that looks like this:

d = [1 2 0 4; 1 0 3 0; 0 0 0 4; 1 0 3 4];

Any tips? How can this be done? How can I do this without using loops?

+1  A: 

Does this work? (Edited: fixed mistake.)

[m,n] = size(c)
d = zeros(m,n)
for i=1:m
    d(i,c(i,c(i,:)>0)) = c(i,c(i,:)>0)
end
Steve
Is there a way to this without using a loop? I'm working with very large data sets and loops tend to be very slow...
Edward
I think it is possible, but in this case, you are doing the same operation to each row, so it makes to loop over each row. Even for large matrices, I don't think a loop would make the procedure prohibitively slow.
Steve
Would you mind sharing the non-look sollution?
Edward
+2  A: 

Here's a vectorized solution:

a = [1 4 2 0; 3 1 0 0; 4 0 0 0; 1 3 4 0];
b = zeros(size(a,1),max(a(:)));
[rowIdx,~] = find(a);
vals = a(a>0);
b( sub2ind(size(b),rowIdx,vals) ) = vals;
Amro
Thanks! This looks great!
Edward

related questions