make adjacent array element the same as current element

1 visualización (últimos 30 días)
Darren Lim
Darren Lim el 27 de En. de 2021
Comentada: Darren Lim el 2 de Feb. de 2021
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

Respuesta aceptada

Alan Moses
Alan Moses el 29 de En. de 2021
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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by