why Monte-Carlo Runs So slowly in a GUI when needing calling some functions

1 Ansicht (letzte 30 Tage)
I'v built a GUI, in which users input a function form like(f*W-1140),and they need to input variable corresponding characters(like f&W in that function),and also numerical matrixs for each variable, for each variable has different distribution pattern, users input number token matrix(1 for normal distribution 2 for lognormal distribution and 3 for extreme value I distribution) so we can call different distribution functions (like pdf、cdf、inv)according to different distribution pattern.
However, this codes runs too slowly, while if users variety is not considered ,and all forms are appointed(distribution patterns are already known, no defined-function needed), it runs for 20s when we circle it for 1e6 times? why?
g=str2sym(get(handles.gnfunc,'string'))%g is the function form users input(sym)
muX=(str2num(get(handles.junzhimatrix,'string')))';%expectation matrix
sigmaX=(str2num(get(handles.fangchamatrix,'string')))';%variance matrix
global n fb
for i=1:n
gX(i)=diff(g,fb(i))
end
m=str2num(get(handles.fenbuleixingdaihaomatirix,'string'));
muXnew=muX,sigmaXnew=sigmaX;
muX1=muX,sigmaX1=sigmaX;
for i=1:n
switch m(i)
case{1}%normal
case{2}%log normal
sigmaXnew(i)=sqrt(log(1+(sigmaX(i)/muX(i))^2)),muXnew(i)=log(muX(i))- sigmaXnew(i)^2/2;%对数正态的方差与期望
case{3}%evI
sigmaXnew(i)=sqrt(6)*sigmaX(i)/pi,muXnew(i)=-psi(1)*sigmaXnew(i)-muX(i);%极值I型的方差与期望
end
end
bt1=cputime;
nS=1000000,nF=0;
x=muX;
for k=1:nS
for i=1:n
x(i)=rndx(m(i),muXnew(i),sigmaXnew(i));
end
g1=int(subs(g,fb,x));
if g1<0
nF=nF+1;
end
disp(k);
end
pf1=nF/nS;
dt1=cputime-bt1;
pf1=num2str(pf1);
dt1=num2str(dt1);
set(handles.cpuzhanshi,'string',dt1);
set(handles.kekaodu,'string',[ ]);
set(handles.kkd,'string',pf1);
guidata(hObject,handles);
function y=rndx(p,q,r)
switch p
case{1}%normal
y=normrnd(q,r)
case{2}%lognormal
y=lognrnd(q,r)
case{3}%evI
y=-evrnd(q,r)
end
  2 Kommentare
Jan
Jan am 28 Nov. 2019
Start with a proper indentation to improve the readability of the code. Use one command per line. Spaces around operators makes the reading easier also.
Then use the profiler to find the bottleneck of the code: where is the most time spent?
Image Analyst
Image Analyst am 28 Nov. 2019
Type control-a (to select all) followed by control-i (to properly indent everything).

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Produkte


Version

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by