Filter löschen
Filter löschen

make adjacent array element the same as current element

5 Ansichten (letzte 30 Tage)
Darren Lim
Darren Lim am 27 Jan. 2021
Kommentiert: Darren Lim am 2 Feb. 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

Akzeptierte Antwort

Alan Moses
Alan Moses am 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by