How can I change the place of two numbers randomnly in a row?
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
Image Analyst
on 5 May 2016
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 Comments
Image Analyst
on 5 May 2016
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.
More Answers (1)
Azzi Abdelmalek
on 5 May 2016
[n,m]=size(a),
out=a(reshape(randperm(n*m),n,m))
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!