Matlab大数组减号

时间:2018-09-10 13:56:35

标签: arrays matlab parfor

我正在尝试优化Matlab代码,以进行大量数据(1e6值)的统计计算。我用diff或基本数学尝试了几种方法,包括循环或有趣的函数。 对我来说,这段代码运行大约8秒钟。虽然,使用附加的for循环可以很好地运行“运行部分”模式,但是在运行脚本时不稳定。

有什么方法可以缩短这段代码的时间。我为parfor尝试了不同的方法,但是无法在循环中进行设置。这里有人对parfor有足够的经验告诉我如何摆脱广播变量问题吗?

%% Matlab Question
L=400000;
t_clk = rand(1, L);
t_clk = t_clk-0.5;
plot (t_clk)
%
disp(' ')
tic
N = 1000; %2000
M = length(t_clk)-N;
temp_Pkp = zeros(1, N);
temp_Pkn = zeros(1, N);
temp_Std = zeros(1, N);
myMat = zeros(1,M);
% Time to execute: 'run section' / 'run' / 'run and time'
%parfor xx = 1 :1  : N  %2.3 -> broadcast variable issues
for xx = 1 :1  : N  %2.3

    myMat =  bsxfun(@minus,t_clk(xx+1 : xx+M) , t_clk(1:M)); %% Time to execute: 8.1s / 8.2s / 7.76s
    %myMat =  t_clk(xx+1 : xx+M) - t_clk(1:M); %% Time to execute: 8.1s / 8s / 86s
    %myMat = zeros(1,M); % not used
    %for yy = 1:1:M %% Time to execute: 4.6s / 4.6s / 23.6s ('run and time' execution time is very high)
    %    myMat(yy) =t_clk(xx+yy) - t_clk(yy);
    %end
    temp_Mean= mean(myMat) ;
    temp_Pkp(xx) = max(myMat(:)) - temp_Mean  ; % max - min
    temp_Pkn(xx) = temp_Mean  - min(myMat(:))  ; % max - min
    temp_Std(xx) = sqrt(sum(sum((myMat-temp_Mean).^2))/M);
end
toc
plot(temp_Std)

1 个答案:

答案 0 :(得分:1)

我做了些摆弄,看来您要反复索引一个变量,这使您付出了很多代价。此变量为t_clk,您每次都按1:M编制索引。如果使用此索引创建临时变量,则可以大大加快运行速度。

%% Matlab Question
L=400000;
t_clk = rand(1, L);
t_clk = t_clk-0.5;
plot (t_clk)
%
disp(' ')
tic
N = 1000; %2000
M = length(t_clk)-N;
temp_Pkp = zeros(1, N);
temp_Pkn = zeros(1, N);
temp_Std = zeros(1, N);
myMat = zeros(1,M);
% Time to execute: 'run section' / 'run' / 'run and time'
%parfor xx = 1 :1  : N  %2.3 -> broadcast variable issues
t_clk_t = t_clk(1:M);
idx = 1:M;
for xx = 1 :1  : N  %2.3

    myMat =  bsxfun(@minus,t_clk(xx+1 : xx+M) , t_clk(1:M)); %% Time to execute: 3.043

    myMat =  bsxfun(@minus,t_clk(xx+1 : xx+M) , t_clk_t); % Time to execute 1.740

%     myMat = t_clk(xx+1 : xx+M) - t_clk(1:M);
    %myMat =  t_clk(xx+1 : xx+M) - t_clk(1:M); %% Time to execute: 8.1s / 8s / 86s
    %myMat = zeros(1,M); % not used
    %for yy = 1:1:M %% Time to execute: 4.6s / 4.6s / 23.6s ('run and time' execution time is very high)
    %    myMat(yy) =t_clk(xx+yy) - t_clk(yy);
    %end
    temp_Mean= mean(myMat) ;
    temp_Pkp(xx) = max(myMat(:)) - temp_Mean  ; % max - min
    temp_Pkn(xx) = temp_Mean  - min(myMat(:))  ; % max - min
    temp_Std(xx) = sqrt(sum(sum((myMat-temp_Mean).^2))/M);
end
toc
plot(temp_Std)