How can I change the place of two numbers randomnly in a row?

1 回表示 (過去 30 日間)
CarenCaren
CarenCaren 2016 年 5 月 5 日
コメント済み: CarenCaren 2016 年 5 月 5 日
How can I change the place of two numbers randomnly in a row in a matrix? For example;
a=[1 0 0 0 0 0;
0 0 1 0 0 0;
0 1 0 0 0 0;
0 0 0 1 0 0];
and , I want to change the places of the numbers in each row. Then I want to find; this matrix:
a=[0 0 1 0 0 0;
0 1 0 0 0 0;
0 0 0 0 1 0;
0 0 0 0 0 1];
How can I write a code for this?

採用された回答

Image Analyst
Image Analyst 2016 年 5 月 5 日
Try this:
m = [45 49 30 47 21 15;
0 73 15 0 27 20;
60 52 24 78 54 0;
75 70 57 61 80 57]
[rows, columns]=size(m);
for row = 1 : rows
twoIndexes = randperm(columns, 2);
index1 = twoIndexes(1);
index2 = twoIndexes(2);
fprintf('In row #%d, swapping column %d with column %d\n', row, index1, index2);
[m(row, index1), m(row, index2)] = deal(m(row, index2), m(row, index1));
end
m % Echo to command window.
It will show this:
m =
45 49 30 47 21 15
0 73 15 0 27 20
60 52 24 78 54 0
75 70 57 61 80 57
In row #1, swapping column 1 with column 3
In row #2, swapping column 5 with column 3
In row #3, swapping column 1 with column 2
In row #4, swapping column 3 with column 2
m =
30 49 45 47 21 15
0 73 27 0 15 20
52 60 24 78 54 0
75 57 70 61 80 57
It does as you requested = swap two column elements in each row.
  3 件のコメント
Image Analyst
Image Analyst 2016 年 5 月 5 日
My answer swaps exactly 2 numbers like you asked for. Azzi's answer swaps them all. The whole row gets scrambled, not just two numbers like you asked for, and like your example showed.
CarenCaren
CarenCaren 2016 年 5 月 5 日
You're right. I checked it, this one is the exact solution that I wanted. Thanks a lot for your help.

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 5 月 5 日
[n,m]=size(a),
out=a(reshape(randperm(n*m),n,m))
  3 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2016 年 5 月 5 日
[n,m]=size(a),
for k=1:n
a(k,:)=a(k,randperm(m))
end
CarenCaren
CarenCaren 2016 年 5 月 5 日
編集済み: CarenCaren 2016 年 5 月 5 日
Thanks a lot for your answer. But this one is not what I asked for.

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by