Swap the first and last columns

26 ビュー (過去 30 日間)
Zunaed Kibria
Zunaed Kibria 2018 年 12 月 16 日
回答済み: ARVIND KUMAR SINGH 2020 年 5 月 25 日
function B = swap_ends(A)
B = A(:,[end , 2:end-1 , 1]);
end
tried this , but showing error , can any one help ?

回答 (4 件)

Alessandro Galo
Alessandro Galo 2019 年 3 月 26 日
This works ;)
if size(A,2) ~= 1 & size(A,2) ~= 0
B = A(:,[end , 2:end-1 , 1])
else
B = A;
end

madhan ravi
madhan ravi 2018 年 12 月 16 日
編集済み: madhan ravi 2018 年 12 月 16 日
A=rand(4) % example matrix
B = swap_ends(A) % function call
function B = swap_ends(A) % function definition
A(:,[1 end])=A(:,[end 1]);
B=A;
end
Gives:
A =
0.5200 0.8475 0.4965 0.0832
0.7875 0.0289 0.0663 0.1867
0.2765 0.5650 0.1179 0.9095
0.0962 0.7098 0.3063 0.6303
B =
0.0832 0.8475 0.4965 0.5200
0.1867 0.0289 0.0663 0.7875
0.9095 0.5650 0.1179 0.2765
0.6303 0.7098 0.3063 0.0962
A=rand(1,5) % example row vector/column vector
B = swap_ends(A) % function call
function B = swap_ends(A) % function definition
A([1 end])=A([end 1]);
B=A;
end
Gives:
A =
0.6604 0.9767 0.4717 0.8576 0.9269
B =
0.9269 0.9767 0.4717 0.8576 0.6604
  1 件のコメント
Walter Roberson
Walter Roberson 2019 年 3 月 26 日
編集済み: Walter Roberson 2019 年 3 月 26 日
Alessandro Galo's solution does raise the good point that swapping using end subscript will fail if the array is empty on that dimension, so the swap should be protected with isempty()

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


Sunil Kumar Giri
Sunil Kumar Giri 2020 年 1 月 13 日
function B = swap_ends(A)
B = A;
A(:,1) = A(:,end);
A(:,end) = B(:,1);
B = A
end

ARVIND KUMAR SINGH
ARVIND KUMAR SINGH 2020 年 5 月 25 日
function B = swap_ends(A)
[~,col] = size(A);
if col<2
B = A;
else
a = A(:,1);
b = A(:,col);
c = A(:,2:col-1);
B =[b c a];
end
end

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by