Swaping two columns randomly picked

3 ビュー (過去 30 日間)
Bartosz Bagrowski
Bartosz Bagrowski 2022 年 5 月 17 日
コメント済み: Bartosz Bagrowski 2022 年 5 月 17 日
Hi guys,
I would like to swap two columns randomly picked in an array. I wrote such a code and I would be glad if you could help me to find the error:
it's an array q with dimensions 25x5. Later I would like to create two another function for inserting one randomly picked column after the second randomly picked column, I would be thankful if you could check and help me.
w=5
function qnew = Swap(q)
n = w;
i=randsample(n,2) %randomly picking two columns
i1=i(1);
i2=i(2);
qnew(:,i(1))=q(:,i(2));
qnew([i1(:,i(1)) i2(:,i(2))])=q([i2(:,i(2)) i1(:,i(1))]);
disp(qnew);
end
Function definitions in a script must appear at the end of the file.
Move all statements after the "Swap" function definition to before the first local function definition.

採用された回答

Torsten
Torsten 2022 年 5 月 17 日
編集済み: Torsten 2022 年 5 月 17 日
A = rand(25,5);
i = randsample(5,2);
v = A(:,i(1));
A(:,i(1)) = A(:,i(2));
A(:,i(2)) = v;
or simply
A = rand(25,5);
i = randsample(5,2);
A(:,[i(1) i(2)]) = A(:,[i(2) i(1)]);
  1 件のコメント
Bartosz Bagrowski
Bartosz Bagrowski 2022 年 5 月 17 日
Thanks, it helped me a lot! And do you have maybe an idea how to insert one randomly picked column after another one randomly picked?

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by