【问题标题】:Using Parfor to create matrix from a vector使用 Parfor 从向量创建矩阵
【发布时间】:2014-11-16 10:16:01
【问题描述】:

我是 Matlab 新手,希望能提供任何帮助!

我正在运行模拟,因此每次模拟运行的结果都会有所不同。我想收集结果进行分析。

例如,在第一次模拟运行期间,血浆凝血因子的水平可能会在 5 小时内发生变化,如下所示: R(1) = [1.0 0.98 0.86 0.96 0.89]

在第二次运行中,每个时间段的水平可能略有不同,例如。 R(2) = [1.0 0.95 0.96 0.89 0.86]

我想(也许通过使用 parfor 函数)创建一个矩阵,例如。 R = [1.0 0.98 0.86 0.96 0.89 1.0 0.95 0.96 0.89 0.86]

我遇到的问题包括“在赋值 A(I) = B 中,B 和 I 中的元素数量必须相同”到获取零或一的矩阵(取决于我用于预分配的内容) )。

我需要模拟运行大约 10000 次才能收集到有意义的结果。

谁能建议如何实现?对于像我这样刚接触 Matlab 的人,非常感谢您提供详细的指导或(半)完整代码。

提前致谢!

这是我的实际代码,如您所见,有 4 个变量在 744 小时(31 天)内变化,我想单独收集它们:

Iterations = 10000;
PGINR = zeros(Iterations, 744);
PGAmount = zeros(Iterations, 744);
CAINR = zeros(Iterations, 744);
CAAmount = zeros(Iterations, 744);

for iii = 1:Iterations
    [{PGINR(iii)}, {PGAmount(iii)}, {CAINR(iii)}, {CAAmount(iii)}] = ChineseTTRSimulationB();
end

filename = 'ChineseTTRSimulationResults.xlsx';
xlswrite(filename, PGINR, 2)
xlswrite(filename, PGAmount, 3)
xlswrite(filename, CAINR, 5)
xlswrite(filename, CAAmount, 6)

【问题讨论】:

    标签: c++ matlab for-loop iteration parfor


    【解决方案1】:

    您是否正在寻找这样的东西? 为了更好地理解,我稍微简化了您的代码,并添加了一些虚拟数据、函数。

    ma​​in.m

    Iterations  = 10;
    PGINR       = zeros(Iterations, 2);
    PGAmount    = zeros(Iterations, 2);
    
    %fake data
    x = rand(Iterations,1);
    y = rand(Iterations,1);
    
    parfor iii = 1:Iterations
        [PGINR(iii,:), PGAmount(iii,:)] = ChineseTTRSimulationB(x(iii), y(iii));
    end
    

    ChineseTTRSimulationB.m

    function [PGINRi, PGAmounti] = ChineseTTRSimulationB(x,y)
        PGINRi       = [x + y, x];
        PGAmounti    = [x*y, y];
    end
    

    【讨论】:

    • 亲爱的Arpi,非常感谢您的建议!我会在当前的模拟运行完成后立即尝试!
    【解决方案2】:

    将每个 parfor-result 保存在单元格中,然后将它们组合起来。

    Iterations = 10000;
    PGINR = cell(1, Iterations);
    PGAmount = cell(1, Iterations);
    CAINR = cell(1, Iterations);
    CAAmount = cell(1, Iterations);
    
    parfor i = 1:Iterations
        [PGINR{i}, PGAmount{i}, CAINR{i}, CAAmount{i}] = ChineseTTRSimulationB();
    end
    
    PGINR = cell2mat(PGINR); % 1x7440000 vector
    %and so on...
    

    【讨论】:

    • 亲爱的兰帕,非常感谢您的建议!我会在当前的模拟运行完成后立即尝试!
    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多