Matlab大数组减去

问题描述 投票:-2回答:1

我正在尝试优化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)
arrays matlab parfor
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.