【问题标题】:Concatenating matrices within for-loop in MatLab在 MatLab 中的 for 循环内连接矩阵
【发布时间】:2014-12-06 13:56:37
【问题描述】:

在 MatLab 中,我有一个尺寸为 22 x 4 的矩阵 SimC。我使用 for 循环重新生成该矩阵 10 次。

我想得到一个矩阵U,它在第 1 到第 22 行中包含 SimC(1),在第 23 到第 45 行中包含 SimC(2),依此类推。因此,U 最终的尺寸应该是 220 x 4。

谢谢!!

编辑:

nTrials = 10;
n = 22;
U = zeros(nTrials * n , 4)      %Dimension of the final output matrix

for i = 1 : nTrials

   SimC = SomeSimulation()    %This generates an nx4 matrix 
   U = vertcat(SimC)   

end    

不幸的是,上述方法不起作用,因为 U = vertcat(SimC) 只返回 SimC 而不是连接。

【问题讨论】:

  • 不妨看看vertcat?
  • 谢谢,vertcat 看起来很有希望。但是我无法让它在代码中工作:

标签: matlab loops matrix populate


【解决方案1】:

vertcat 是一个不错的选择,但它会导致矩阵不断增长。这对于大型程序来说不是很好的做法,因为它确实会减慢速度。但是,在您的问题中,您不会循环太多次,所以vertcat 很好。

要使用vertcat,您不会预先分配U 矩阵的完整最终大小...只需创建一个空的U。然后,在调用vertcat 时,您需要给它两个要连接的矩阵:

nTrials = 10;
n = 22;
U = []      %create an empty output matrix
for i = 1 : nTrials
    SimC = SomeSimulation();    %This generates an nx4 matrix
    U = vertcat(U,SimC);  %concatenate the two matrices 
end  

由于您已经知道最终大小,因此更好的方法是预先分配您的全部 U(就像您所做的那样),然后通过计算正确的索引将您的值放入 U。像这样的:

nTrials = 10;
n = 22;
U = U = zeros(nTrials * n , 4);      %create a full output matrix
for i = 1 : nTrials
    SimC = SomeSimulation();    %This generates an nx4 matrix
    indices = (i-1)*n+[1:n];  %here are the rows where you want to put the latest output
    U(indices,:)=SimC;  %copies SimC into the correct rows of U 
end 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    相关资源
    最近更新 更多