# replace elements in an Array with other elements

50 visualizzazioni (ultimi 30 giorni)
Rica il 20 Lug 2015
Commentato: Juan Jiménez il 22 Giu 2020
hi all,
i have the folwing situation:
i have an array:
A=[1 2 3 4 4 4 5 8 7 4 6 4]
i want to find the element equal to the value 4.
I do this:
index=find(A==4)
i want now to replace the element with this index with the previous value. it means i want to get:
A_new=[1 2 3 3 3 3 5 8 7 7 6 6].
i did it with a loop. is there any method without loop?
thank you
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Guillaume il 20 Lug 2015
While it may be possible to do it without a loop, with a combination of diff, find and possibly cumsum it's going to be a lot more obscure than a simple loop and probably not any more efficient.
The simplest loop would be:
for idx = find(A == 4)
A(idx) = A(idx-1);
end
which also works for consecutive elements to replace.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Juan Jiménez il 22 Giu 2020
Excellent! I need this. Thank you so much.

Accedi per commentare.

### Più risposte (3)

Walter Roberson il 20 Lug 2015
A_new = A;
A_new(index) = A(index-1);
This will fail if the very first thing was a 4, as there is no "previous" for the first element.
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Guillaume il 20 Lug 2015
This also fails on the example given, when there are consecutive elements to replace.

Accedi per commentare.

Sean il 20 Lug 2015
Modificato: Sean il 20 Lug 2015
A=[1 2 3 4 4 4 5 8 7 4 6 4]
idx = find(A~=4);
B = interp1(idx,A(idx),1:numel(A),'previous','extrap')
Gotta love the 'previous' and 'next' options added to interp1 a few releases ago!
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Shashank il 14 Giu 2018
How can I copy paste 2nd element to 3rd, 3rd to 4th and so on.. A=[1,2,3,4,5,6,7]; A_New=[1,2,2,3,3,4,4,5,5,6,6,7]; ---> Required
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Whos 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