MATLAB: How to change the place of two numbers randomnly in a row

matrix

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?

Best Answer

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.