重复某些矩阵的值

时间:2012-07-19 15:47:01

标签: matlab matrix repeat

我有矩阵

A = [ 5 6 7;
      7 5 6 ]

B = [ 1 2 3;
      3 1 2 ]

C = [ 1 0 2;
      0 2 1 ]

Start time A = [ 2 3 7;
                 1 6 8 ]

Start time C = [ 1 0 5;
                 0 4 7 ]

问题:我想通过使用矩阵B重复矩阵A.我还有矩阵开始时间A,它是我们必须放置矩阵A的每个值的开始列。 然后我必须输入值“0”,与矩阵C的每个值(矩阵C重复值“0”)在列号中作为矩阵“开始时间C”的值并且在放入每个矩阵A的值之前

所以我必须在矩阵下面输出这样的输出:

Result = [ 0 5 6 6 0 0 7 7 7;
           7 7 7 0 0 5 0 6 6 ]

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

一种可能的解决方案如下。请注意,我可以自由地为变量分配有意义的名称,因为AStart Time A(甚至不是有效的Matlab标识符)等名称很容易混淆。你也可以看到你的矩阵 CStart Time C是多余的,因为所有信息都已在A中编码, BStart Time A

% The values to put in the result matrix.
value = [5 6 7;
         7 5 6];
% Column index where each sequence starts in the result matrix.
start = [2 3 7;
         1 6 8];
% The length of each sequence, i.e. how often to put the value into the result.
count = [1 2 3;
         3 1 2];

% Determine the longest row. Note: At this place you could also check, if all 
% rows are of the same length. The current implementation pads shorter rows with
% zeros.
max_row_length = max(start(:, end) + count(:, end) - 1);

% Allocate an output matrix filled with zeros. This avoids inserting sequences
% of zeros afterwards.
result = zeros(size(start, 1), max_row_length);

% Finally fill the matrix using a double loop.
for row = 1 : size(start, 1)
    for column = 1 : size(start, 2)
        s = start(row, column);
        c = count(row, column);
        v = value(row, column);
        result(row, s : s + c - 1) = v;
    end
end

result

result =

     0     5     6     6     0     0     7     7     7
     7     7     7     0     0     5     0     6     6

按要求。