Simbi
Simbi

Reputation: 1042

Replace zero values in vector

Ive got a vector like this

a=[0 5 3 0 1]

and a corresponding vector, containing the same amount of numbers as there are zeros in the first vector

b=[2 4]

what I want to get is

x=[2 5 3 4 1]

I tried fiddling around with, and somewhat got the feeling that the find / full methods might help me here, but didn't get it to work

c=(a==0) 
>[1 0 0 1 0]

Thank you!

Upvotes: 0

Views: 536

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

It is as easy as this:

x=a;

As x==0 gives the vector of all the locations an element = 0, ie [0 1 0 0 1], x(x==0) is indexing x to get the actual elements of x that are equal to 0, which you can then assign values as if it were any other vector/matrix (where the values we are not interested in do not exist, and are not indexed), using the following:

x(x==0)=b;

Upvotes: 3

Related Questions