MATLAB: Make adjacent array element the same as current element

transform adjacent array elements

Dear Community ,
I have an array : say [ 0 0 1 0 0 0 1 1 1 0 0 0 1 0 ]
If the array has 1 , i want to make it such that the neighbouring element (left and right ) will turn into 1 .
sample before [ 0 0 1 0 0 0 1 1 1 0 0 0 1 0 ]
sample after [ 0 1 1 1 0 1 1 1 1 1 0 1 1 1 ]
Is there any way to do this without a for loop ? any function that works like transformAdjArrayOnes()? Thanks in advance!
Darren

Best Answer

You may refer to the piece of code below that uses the find function to achieve your goal without using a loop.
function y = transformAdjArrayOnes(a)
y = a; %copying the input array
loc = find(a==1); %finding locations of 1
y(loc+1) = 1; %making right adjacent element to 1
y(loc-1) = 1; %making left adjacent element to 1
end
You may call the above function with your sample array as follows:
>> a = [ 0 0 1 0 0 0 1 1 1 0 0 0 1 0 ]
a =
0 0 1 0 0 0 1 1 1 0 0 0 1 0
>> transformAdjArrayOnes(a)
ans =
0 1 1 1 0 1 1 1 1 1 0 1 1 1