【问题标题】:Concatenate matrices with different start index and different end index (Aligning)连接具有不同起始索引和不同结束索引的矩阵(对齐)
【发布时间】:2015-07-26 05:25:34
【问题描述】:
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[max length of (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,我只是不知道如何执行这个想法,尤其是在循环中。

【问题讨论】:

    标签: matlab matrix concatenation


    【解决方案1】:

    如果我的问题在我的脑海中正确,似乎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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多