make adjacent array element the same as current element

1 回表示 (過去 30 日間)
Darren Lim
Darren Lim 2021 年 1 月 27 日
コメント済み: Darren Lim 2021 年 2 月 2 日
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

採用された回答

Alan Moses
Alan Moses 2021 年 1 月 29 日
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 件のコメント
Darren Lim
Darren Lim 2021 年 2 月 2 日
Thanks Alan! Works perfectly and elegantly :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by