Re-arranging array columns in alternating form

I would like to write a function:
function [Y]=AlternateColumns(X,n)
that takes an array X of the form:
AlterBefore.png
and turns it into Y of the form:
AlterAfter.png
In this example n=3, but it could be any number by which the entire number of columns is divisible. How is this possible without using a loop?

 採用された回答

Guillaume
Guillaume 2018 年 12 月 18 日
編集済み: Guillaume 2018 年 12 月 18 日

1 投票

function Y = AlternateColumns(X, n)
Y = reshape(permute(reshape(X, size(X, 1), [], n), [1 3 2]), size(X, 1), []);
end
Basically, reshape into a 3D array, swap dimensions 2 and 3 and reshape back into original shape.

1 件のコメント

Saeid
Saeid 2018 年 12 月 18 日
Brilliant! Thanks Guillaume!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2018 年 12 月 18 日

コメント済み:

2018 年 12 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by