## Filling vector with a condition.

### Javier (view profile)

on 9 May 2013
Accepted Answer by Stephan M. H.

### Stephan M. H. (view profile)

Hi.

I have two vectors A and B of the same length

I wan´t to create a new vector containing the same numbers of B, but only if the same element in A was a number>0, if not, i want to put a zero in that element.

How can i do this? Could you help me?

## Products

No products are associated with this question.

### Stephan M. H. (view profile)

on 9 May 2013
Edited by Stephan M. H.

### Stephan M. H. (view profile)

on 9 May 2013

Hi Javier,

as far as I understood your question you want to create a new vector with

``` for i=1:lenght(A)
if A(i)>0
C(i) = B(i)
end
end```

This could be done in with the for loop above, but the fastest way should be via logical indexing.

` C = zeros(size(A));`
` flag_a = A >0   % is logical 1 where elements are bigger zero `
` C(flag_a) = B(flag_a);`

best, Stephan

Javier

### Javier (view profile)

on 9 May 2013

Gracias totales!! Thank you!

### John Doe (view profile)

on 9 May 2013
Edited by John Doe

### John Doe (view profile)

on 9 May 2013

Like this?

```A = [1 2 -3 0 4 0 -5 0 6];
B = 10:19;
C = zeros(1,length(A));
```
```C(A>0) = B(A>0)
```
```C =
```
`      10    11     0     0    14     0     0     0    18`

Javier

### Javier (view profile)

on 9 May 2013

Thank you!

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi