我想选择矩阵的两个随机列并交换它们。我用:
S(:,[round_i round_j]) = S(:,[round_j round_i]);
但是我的代码似乎产生了和以前一样的矩阵。下面是代码片段和命令窗口的输出。
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是我传递给函数swapRounds()
的矩阵。输出如下所示:
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
如何让这段代码交换我的两列?
答案 0 :(得分: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
基本上,您应该使用数组索引列,而不仅仅是两个数字。见this highly informative post on indexing in MATLAB