make adjacent array element the same as current element

1 vue (au cours des 30 derniers jours)
Darren Lim
Darren Lim le 27 Jan 2021
Commenté : Darren Lim le 2 Fév 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

Réponse acceptée

Alan Moses
Alan Moses le 29 Jan 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
  1 commentaire
Darren Lim
Darren Lim le 2 Fév 2021
Thanks Alan! Works perfectly and elegantly :)

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by