连接具有不同起始索引和不同结束索引的矩阵(对齐)

Concatenate matrices with different start index and different end index (Aligning)

for i = 1 : numel(T);
    j = 1 : numel(T(i).n);
P(i,j) = (T(i).n);
G(i) = (T(i).lastPulse)-1100;
Y = P(1,G(1):length(T(1).n));
S = P(2,G(2):length(T(2).n));
end

我有前面的代码。 P 是一个 (191x10000) 矩阵。我想取出每一行的特定部分,如我在 S 和 Y 中所示,然后连接 S 和 Y 以及对应于 P 的其他行的其他行矩阵以创建矩阵 A(191x[最大长度 (S,Y,. ..)])。但棘手的部分是我无法使 S 和 Y 对齐。

示例:

P = [1 2 1 3 1 1 1 0 3 1 0]
    [3 0 2 0 1 1 4 1 1 2 0];
S = P(1,1:7) = [1 2 1 3 1 1 1];
Y = P(2,5:10) = [1 1 4 1 1 2];
% A = concatenated S and Y aligned to original P. 
A = [ 1   2   1   3   1   1   1  nan nan nan nan]
    [nan nan nan nan  1   1   4   1   1   2  nan];

我最好使用循环而不是分离矩阵,例如 S 和 Y,因为我有很多行。

建议的答案:

我有一个想法,可能我必须使用对应于 P 的索引并使用它们来连接 Y 和 S,我只是不知道如何执行这个想法,尤其是在循环中。

如果我在脑海中 正确地回答了问题,那么这里似乎 bsxfun 可以用来创建一个掩码,然后将被掩码的元素从 P,因此有一个对齐的输出。这是一个遵循这些原则的实现 -

%// Random input array
P = randi(9,5,11)

%// Define the start and stop(end) indices as vectors
start_idx = [1 5 3 4 11]
stop_idx = [7 10 3 6 11]

%// Get the size of P and initialize output array
[M,N] = size(P); 
P_out = NaN(M,N); 

%// Create the mask for extracting specific elements from P
mask = bsxfun(@le,start_idx(:),1:N) & bsxfun(@ge,stop_idx(:),1:N);

%// Put masked elements from P into output array
P_out(mask) = P(mask)

另一种无需初始化即可获取输出的方法是这样的 -

P_out = P.*mask;
P_out(~mask) = NaN;

因此,为了与问题中使用的变量相关联,start_idx 将是 G,而 stop_idx 将是 [length(T(1).n),length(T(2).n).length(T(3).n),...]

样本运行-

P =
     1     6     8     8     8     1     9     1     2     4     2
     8     8     6     3     7     6     7     2     5     1     2
     6     8     9     5     6     6     6     8     6     5     2
     9     9     5     9     3     7     9     5     1     2     1
     7     1     5     6     6     9     6     8     6     2     6
start_idx =
     1     5     3     4    11
stop_idx =
     7    10     3     6    11
P_out =
     1     6     8     8     8     1     9   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN     7     6     7     2     5     1   NaN
   NaN   NaN     9   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN
   NaN   NaN   NaN     9     3     7   NaN   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN   NaN     6