# Replace some values of a vector with another vector which has a different size

3 visualizzazioni (ultimi 30 giorni)
Christina il 29 Apr 2015
Commentato: Stephen23 il 29 Apr 2015
Hello
I've got the vector: source = [ 0 0 1 0 1]
and the vector a = [2 3],
which has a different size to source.
I'd like to replace in the source vector the elements that are equal to 1, with those of vector a.
The final vector b should be: b = [0 0 2 0 3]
Any thoughts on this?
Thank you!
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Thorsten il 29 Apr 2015
Modificato: Thorsten il 29 Apr 2015
source(source == 1) = a
##### 2 CommentiMostra NessunoNascondi Nessuno
Christina il 29 Apr 2015
Thank you! It works!
pfb il 29 Apr 2015
However, that changes "source" instead of creating "b", as asked in the question.

Accedi per commentare.

### Più risposte (2)

pfb il 29 Apr 2015
b=zeros(size(source));
b(find(source))=a;
of course this works only if the number of nonzero elements in source are the same as the elements in a.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Christina il 29 Apr 2015
Thank you! It works

Accedi per commentare.

Stephen23 il 29 Apr 2015
Modificato: Stephen23 il 29 Apr 2015
This can be achieved very simply using basic logical indexing:
>> A = [ 0 0 1 0 1];
>> B = [ 2 3];
>> A(A==1) = B
A = 0 0 2 0 3
On my computer this was almost twice as fast compared to using find and zeros.
##### 3 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
James Tursa il 29 Apr 2015
Stephen switched nomenclature. His starting "A" is your "source" his "B" is your "a", and his resulting "A" is your "b".
Stephen23 il 29 Apr 2015
Guilty as charged.

Accedi per commentare.

### Categorie

Scopri di più su Environment and Settings in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by