Matlab 2016b:使用结构循环比使用变量

时间:2017-09-05 14:30:35

标签: matlab profiling

我正在计算变量u的错误统计列表。每当我将结构放入循环中时,Matlab就会变得超级低,而标准变量则相当快。我听说使用Matlab 2016b可以使用循环或使用矢量化表示法,速度应该相同。看起来它对结构不起作用。你知道为什么吗?最好的建议在这里?这是一个最小的例子(我只是使用了琐碎的"如果"条款,我的更复杂,这是我不进行矢量化的主要原因):

    n = 1000,
    m = 1000;
    uMODEL = rand(n,m);
    uOBS = rand(n,m);
    %
    %
    %
    tic
    ERRORS = struct('Emedio',0,'MAE',0,'sigma',0,'Emax',0,'Emin',0);
    Nerr(1:max(n,1),1) = 0; %Nerr at most it contains n
    fields = fieldnames(ERRORS);
    for i = 1:numel(fields)
        ERRORS.(fields{i}) = zeros(max(n,1),1);
    end

    for i=1:m
        for j=1:n
        if (1000>2 && 2000<343532)
            diff  = uMODEL(j,i)-uOBS(j,i);
            ERRORS.Emedio(j) = ERRORS.Emedio(j) + diff;
            ERRORS.MAE(j)    = ERRORS.MAE(j)     + abs(diff);
            ERRORS.sigma(j)  = ERRORS.sigma(j)  + diff^2;
            ERRORS.Emax(j)  = max(ERRORS.Emax(j),diff);
            ERRORS.Emin(j) = min(ERRORS.Emin(j),diff);
            Nerr(n)    = Nerr(n) + 1;
        end
        end
    end
    ERRORS.Emedio(:) = ERRORS.Emedio(:)./Nerr(:);
    ERRORS.MAE(:)    = ERRORS.MAE(:)./Nerr(:);
    ERRORS.sigma(:)  = sqrt(ERRORS.sigma(:)./(Nerr(:)-1));


    toc
    clear  ERRORS
    tic
    %
    % here instead I define variables, I fill them up and then I throw them in structures, cause loops with structures are strangely slow...
    Emedio = zeros(max(n,1),1);
    MAE = zeros(max(n,1),1);
    sigma = zeros(max(n,1),1);
    Nerr = zeros(max(n,1),1);
    Emax = zeros(max(n,1),1);
    Emin = zeros(max(n,1),1);

    for i=1:m
        for j=1:n
        if (1000>2 && 2000<343532)
            diff  = uMODEL(j,i)-uOBS(j,i);
            Emedio(j) = Emedio(j) + diff;
            MAE(j)    = MAE(j)     + abs(diff);
            sigma(j)  = sigma(j)  + diff^2;
            Emax(j)  = max(Emax(j),diff);
            Emin(j) = min(Emin(j),diff);
            Nerr(n)    = Nerr(n) + 1;
        end
        end
    end
    Emedio(:) = Emedio(:)./Nerr(:);
    MAE(:)    = MAE(:)./Nerr(:);
    sigma(:)  = sqrt(sigma(:)./(Nerr(:)-1));

    ERRORS.Emedio(:) = Emedio(:);
    ERRORS.MAE(:)    = MAE(:);
    ERRORS.sigma(:)  = sigma(:);
    ERRORS.Emax(:)   = Emax(:);
    ERRORS.Emin(:)   = Emin(:);
    toc

输出是:

  Elapsed time is 2.372765 seconds.
  Elapsed time is 0.057719 seconds.

0 个答案:

没有答案