MATLAB: Replace elements in an Array with other elements

find

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

Best Answer

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.