一种可能的解决方案如下。请注意,我自由地为您的变量分配有意义的名称,因为诸如A
和Start Time A
(甚至不是有效的 Matlab 标识符)之类的名称非常容易混淆。您还可以看到您的矩阵
C
和Start Time C
是多余的,因为所有信息都已经编码在A
和
B
中Start 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
按照要求。
如何修改上述代码以解决 3D 矩阵。
示例:第三维的大小为 2。矩阵值
value(:,:,1) = [5 6 7;
7 5 6];
value(:,:,2) = [6 5 7;
6 7 5];
start(:,:,1) = [2 3 7;
1 6 8];
start(:,:,2) = [1 5 6;
2 5 9];
count(:,:,1) = [1 2 3;
3 1 2];
count(:,:,2) = [2 1 3;
2 3 1];
我希望我的结果矩阵是
result(:,:,1) =[0 5 6 6 0 0 7 7 7;
7 7 7 0 0 5 0 6 6]
result(:,:,2) =[6 6 0 0 5 7 7 7 0;
0 6 6 0 7 7 7 0 5]
如何制作代码以产生结果。谢谢