0

I want to select two random columns of a matrix and swap them. I use:

S(:,[round_i round_j]) = S(:,[round_j round_i]);

But my code seems to produce the same matrix as before. Below are a code snippet and output of the command window.

function swapped_schedule=swapRounds(S)
global weeks;

round_i=randi(weeks)
round_j=randi(weeks)

while round_j~=round_i
    round_j=randi(weeks);
end

S(:,[round_i round_j]) = S(:,[round_j round_i]);

swapped_schedule=S;

end

Schedule is the matrix I pass to the function swapRounds(). The output is shown as follows:

schedule =

     4    -4    -6     5    -2     6     2     3    -5    -3
     5    -6    -4     4     1     3    -1    -5    -3     6
    -6     5    -5     6     4    -2    -4    -1     2     1
    -1     1     2    -2    -3     5     3    -6     6    -5
    -2    -3     3    -1    -6    -4     6     2     1     4
     3     2     1    -3     5    -1    -5     4    -4    -2


round_i =

     4


round_j =

     6


ans =

     4    -4    -6     5    -2     6     2     3    -5    -3
     5    -6    -4     4     1     3    -1    -5    -3     6
    -6     5    -5     6     4    -2    -4    -1     2     1
    -1     1     2    -2    -3     5     3    -6     6    -5
    -2    -3     3    -1    -6    -4     6     2     1     4
     3     2     1    -3     5    -1    -5     4    -4    -2

How do I get this code to swap my two columns?

Adriaan
  • 17,741
  • 7
  • 42
  • 75

1 Answers1

1
schedule = rand(6,10);
round_i = 4;
round_j = 6;

[rows,cols] = size(schedule); % get number of cols
colIDX = 1:cols; % create an index array
colIDX(round_i) = round_j;
colIDX(round_j) = round_i; % flip indices

schedule2 = schedule(:,colIDX); % rename to schedule if wanted

Basically you should index your columns with an array, not just two numbers. See this highly informative post on indexing in MATLAB

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Thanks for the help. But I seem to have put a negation in my while loop which seems to be logically wrong. Just fixed that, now it's working. Thank you anyways. – jannela vignendra Mar 09 '18 at 11:46