How can I change the place of two numbers randomnly in a row?
1 回表示 (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
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
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.
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!