【问题标题】:composing small matrices to a large matrix inside a for loop in Matlab在Matlab中的for循环内将小矩阵组合成一个大矩阵
【发布时间】:2014-10-06 14:34:24
【问题描述】:

假设我们有一个函数,它有一些输出,包括一些数字和矩阵

[A,a,B,n,m] = func(file)

file 作为输入每次都不同,func 将在循环for 中读取它。 矩阵B 始终有两列,其中的行取决于输入文件和func 内部的计算。 现在我想每次在输出中保存这些矩阵B。迭代次数是固定的,比如 10 次。

for 循环是这样的

for i=1:10
    ..... %// here reads the name of the input file which differs each iteration
    [A,a,B,n,m] = func(file)
    .....
end

有什么建议吗?

【问题讨论】:

    标签: matlab for-loop matrix


    【解决方案1】:

    使用元胞数组:

    B_all = cell(1, 10);
    for i=1:10
            % here reads the name of the input file which differs each iteration
    
            [A,a,B,n,m] = func(file);
            B_all{i} = B;
    
            % Continue calculation here
    end;
    

    如果你想最后合并它们(即有一个包含 2 列的单个矩阵):

    B_merged = vertcat(B_all{:});
    

    【讨论】:

    • 非常感谢。只有一条关于合并的评论。我知道当行数不相同时,不可能水平合并它们。但是我们是否有可能选择最大的行并为其他小行放置符号'-'?
    • @Royeh 可以将它们扩展到最大的行数。但在尝试将“-”放入新创建的行之前,您确定您的 Bchar 矩阵吗?还是一个数字矩阵?
    • @CST_Link 当然是数字,然后可以用零代替。
    • @Royeh。还可以考虑将 NaN 作为空值占位符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    相关资源
    最近更新 更多