Script too Long to Run

조회 수: 2 (최근 30일)
Charles Thomas
Charles Thomas 2022년 3월 27일
답변: Sulaymon Eshkabilov 2022년 3월 28일
I've just finish creating the script on one of the Optimisation Method. The problem that I currently have is the script took around 20 minutes
I've also preallocate changing vectors, but that hasn't made any difference. Not sure what I can do to resolve this?
clear
clc
format long
syms X1 X2 X3 X4 real;
%Preallocating changing vectors
x1=zeros(10000,1);
x2=zeros(10000,1);
x3=zeros(10000,1);
x4=zeros(10000,1);
error=zeros(10000,1);
A=[1 0 -1 3; 0 2 1 0; -1 1 6 -1; 3 0 -1 10];
b=[0; -2; -1; -1];
X=[X1; X2; X3; X4];
f=@(X1, X2, X3, X4) (1/2)*X'*A*X + b'*X;
x1(1)=0; x2(1)=1; x3(1)=0; x4(1)=0;
g=A*X+b;
alpha=0.1;
tol=10^(-6)
k=1;
gl = subs(g, [X1, X2, X3, X4], [x1(k), x2(k), x3(k), x4(k)]);
while norm(gl)>tol
gl = subs(g, [X1, X2, X3, X4], [x1(k), x2(k), x3(k), x4(k)]);
alpha=gl'*gl./(gl'*A*gl);
x1(k+1)=x1(k)-alpha*gl(1);
x2(k+1)=x2(k)-alpha*gl(2);
x3(k+1)=x3(k)-alpha*gl(3);
x4(k+1)=x4(k)-alpha*gl(4);
error(k)=norm(gl);
k=k+1;
end
  댓글 수: 2
Stephen23
Stephen23 2022년 3월 27일
"Not sure what I can do to resolve this?"
Don't use the symbolic toolbox. Numeric operations are much faster.
Charles Thomas
Charles Thomas 2022년 3월 27일
Thank you very much! Just removed "syms", and made some few changes before running the loop. Never realise that is the cause of the immeasurable run time for my script, but I really appreciate your help.

댓글을 달려면 로그인하십시오.

채택된 답변

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2022년 3월 28일
Here is a little simplified version of your code:
clc
format long
n=1e4;
x1=zeros(n,1);
x2=x1;
x3=x1;
x4=x1;
error=x1;
A=[1 0 -1 3; 0 2 1 0; -1 1 6 -1; 3 0 -1 10];
b=[0; -2; -1; -1];
x1(1)=0; x2(1)=1; x3(1)=0; x4(1)=0;
g=@(y1,y2, y3, y4)(A*([y1; y2; y3; y4])+b);
alpha=0.1;
tol=1e-6;
k=1;
gl =g(x1(k), x2(k), x3(k), x4(k));
while norm(gl)>tol
gl = g(x1(k), x2(k), x3(k), x4(k));
alpha=gl'*gl./(gl'*A*gl);
x1(k+1)=x1(k)-alpha*gl(1);
x2(k+1)=x2(k)-alpha*gl(2);
x3(k+1)=x3(k)-alpha*gl(3);
x4(k+1)=x4(k)-alpha*gl(4);
error(k)=norm(gl);
k=k+1;
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by