移动矩阵的版本

时间:2014-09-12 04:57:49

标签: matlab matrix combinatorics

我有一个m-by-n矩阵,我想将每个行元素移位k no。时间(“每一个移位一个合成矩阵,因此对应于每一行的k个矩阵总共移位”)(k对于不同的行可以是不同的并且0 <= k <= n)并且想要索引对应的所有合成矩阵每个班次。

例如:我有矩阵:[1 2 3 4; 5 6 7 8; 2 3 4 5]。现在,比方说,我想将row1移位2倍(即row1的k = 2)和row2的3倍(即row2的k = 3)并且想要索引所有移位的矩阵版本(它类似于行的组合但每行的班次有限且不同。)

有人可以帮助编写代码吗? (请帮助编写一般代码,但不是我在这里提到的例子)

我发现以下问题在某种程度上有用,但它不能解决我的问题,因为我的问题看起来像这个问题的一个特例:

Matlab: How to get all the possible different matrices by shifting it's rows (Update: each row has a different step)

2 个答案:

答案 0 :(得分:0)

看看这是否适合你 -

%// Input m-by-n matrix
A = rand(2,5) %// Edit this to your data

%// Initialize shifts, k for each row. The number of elements would be m.
sr = [2 3];   %// Edit this to your data

[m,n] = size(A); %// Get size

%// Get all the shits in one go
sr_ind = arrayfun(@(x) 0:x,sr,'un',0);   %//'
shifts = allcomb(sr_ind{:},'matlab')';  %//'

for k1 = 1:size(shifts,2)

    %// Get shift to be used for each row for each iteration
    shift1 = shifts(:,k1);

    %// Get circularly shifted column indices
    t2 = mod(bsxfun(@minus,1:n,shift1),n);
    t2(t2==0) = n; 

    %// Get the linear indices and use them to index into input to get the output
    ind = bsxfun(@plus,[1:m]',(t2-1)*m);  %//'
    all_matrices = A(ind) %// outputs
end

请注意,此代码使用MATLAB文件交换代码 allcomb

答案 1 :(得分:0)

如果您的问题实际上并不比您向我们展示的那么复杂,那么可以通过双循环来完成。但是,我不喜欢我的解决方案,因为您需要为要移动的每一行设置另一个嵌套循环。它还会从您给定的k值生成所有移位组合,因此它有很多开销。但这可以是一个开始:

% input
m = [1 2 3 4; 5 6 7 8; 2 3 4 5];
shift_times = {0:2, 0:3};   % 2 times for row 1, 3 times for row 2

% desird results
desired_matrices{1} = [4 1 2 3; 5 6 7 8; 2 3 4 5];
desired_matrices{2} = [3 4 1 2; 5 6 7 8; 2 3 4 5];
desired_matrices{3} = [1 2 3 4; 8 5 6 7; 2 3 4 5];
desired_matrices{4} = [4 1 2 3; 8 5 6 7; 2 3 4 5];
desired_matrices{5} = [3 4 1 2; 8 5 6 7; 2 3 4 5];

% info needed:
[rows, cols] = size(m);
count = 0;

% make all shift combinations
for shift1 = shift_times{1}
    % shift row 1
    m_shifted = m;  
    idx_shifted = [circshift([1:cols]',shift1)]';
    m_shifted(1, :) = m_shifted(1, idx_shifted);

    for shift2 = shift_times{2}
        % shift row 2
        idx_shifted = [circshift([1:cols]',shift2)]';
        m_shifted(2, :) = m_shifted(r_s, idx_shifted);       

        % store them
        store{shift1+1, shift2+1} = m_shifted;
    end
end

% store{i+1, j+1} stores row 1 shifted by i and row 2 shifted by j
% example
all(all(store{2,1} == desired_matrices{1}))  % row1: 1, row2: 0
all(all(store{2,2} == desired_matrices{4}))  % row1: 1, row2: 1
all(all(store{3,2} == desired_matrices{5}))  % row1: 2, row2: 1