swap values of an array

84 ビュー (過去 30 日間)
Mazhar Ali
Mazhar Ali 2019 年 2 月 1 日
コメント済み: madhan ravi 2019 年 2 月 1 日
Hi! Every one
I have an array O = [11 12 13 21 14 22 23 31 25 24 32 33 34] ;
I want to swap a value with its adjacent value at two positions.The postions are defined by vector
v=[5 10]
I want output to be like
out = [11 12 13 21 22 14 23 31 25 32 24 33 34];
The number 14 is replaced by its adjacent 22 at postion 5.
Similarly,
The number 24 is replaced by its adjacent 32 in posioton 10.

回答 (2 件)

Guillaume
Guillaume 2019 年 2 月 1 日
Trivially done:
O = [11 12 13 21 14 22 23 31 25 24 32 33 34];
v = [5 10];
O([v;v+1]) = O([v+1;v]); %v must be a row vector for this to work.
  2 件のコメント
Luna
Luna 2019 年 2 月 1 日
+1
madhan ravi
madhan ravi 2019 年 2 月 1 日
O([v v+1])=O([v+1 v]) % also this works

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


Luna
Luna 2019 年 2 月 1 日
Hi Mazhar Ali,
Try this below:
for i = 1:numel(v)
temp = O(v(i));
replacemnt = O(v(i)+1);
O(v(i)) = replacemnt;
O(v(i)+1) = temp;
end

カテゴリ

Help Center および File ExchangeRead, Write, and Modify Image についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by