I am getting this preallocation warning

댓글 수: 5

Jan
Jan 2022년 11월 19일
편집: Jan 2022년 11월 19일
Please post code as formatted text, not as screen shot. Then it can by re-used by copy&paste to create an answer.
Your get this warning. Correct. So what is your question?
clear; clc; close all
% Function Definition (Enter your Function here):
syms X Y;
f = 100*(Y-(X^2))^2 + (1-X)^2;
% Initial Guess (Choose Initial Guesses):
x(1) = -1.1;
y(1) = 0.5;
e = 10^(-3); % Convergence Criteria
i = 1; % Iteration Counter
% Gradient and Hessian Computation:
df_dx = diff(f, X);
df_dy = diff(f, Y);
J = [subs(df_dx,[X,Y], [x(1),y(1)]) subs(df_dy, [X,Y], [x(1),y(1)])]; % Gradient
ddf_ddx = diff(df_dx,X);
ddf_ddy = diff(df_dy,Y);
ddf_dxdy = diff(df_dx,Y);
ddf_ddx_1 = subs(ddf_ddx, [X,Y], [x(1),y(1)]);
ddf_ddy_1 = subs(ddf_ddy, [X,Y], [x(1),y(1)]);
ddf_dxdy_1 = subs(ddf_dxdy, [X,Y], [x(1),y(1)]);
H = [ddf_ddx_1, ddf_dxdy_1; ddf_dxdy_1, ddf_ddy_1]; % Hessian
S = inv(H); % Search Direction
% Optimization Condition:
while norm(J) > e
I = [x(i),y(i)]';
lam = J*J'./(J*H*J');
x(i+1) = I(1)-lam*S(1,:)*J';
y(i+1) = I(2)-lam*S(2,:)*J';
i = i+1;
J = [subs(df_dx,[X,Y], [x(i),y(i)]) subs(df_dy, [X,Y], [x(i),y(i)])]; % Updated Jacobian
ddf_ddx_1 = subs(ddf_ddx, [X,Y], [x(i),y(i)]);
ddf_ddy_1 = subs(ddf_ddy, [X,Y], [x(i),y(i)]);
ddf_dxdy_1 = subs(ddf_dxdy, [X,Y], [x(i),y(i)]);
H = [ddf_ddx_1, ddf_dxdy_1; ddf_dxdy_1, ddf_ddy_1]; % Updated Hessian
S = inv(H); % New Search Direction
end
x(i+1) = I(1)-lam*S(1,:)*J';
y(i+1) = I(2)-lam*S(2,:)*J';
In this lines of code i recieved a warming from matlab about preallocating for speed, and i don't know how to preallocate
Jan
Jan 2022년 11월 19일
@Vânia Gonçalves: A general hint is to search in the net at first. Asking an internet search engine for "Matlab preallocate" shows useful explanations already.
hi
i already searched in the internet, but i didn´t find any usefull explanation, so i hoped find help here.
but thanks anyawy

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

답변 (2개)

Steven Lord
Steven Lord 2022년 11월 19일

1 개 추천

This is a Code Analyzer warning not a run-time warning.
If you're not sure what preallocation is, why it can be important, or how to do it see the first example on this documentation page.
Jan
Jan 2022년 11월 19일
이동: Jan 2022년 11월 19일

0 개 추천

Seriously? If I ask Google, I get e.g.:
For your code:
...
maxIter = 1000;
x = zeros(maxIter, 1);
y = zeros(maxIter, 1);
while norm(J) > e && i < maxIter
...
end
x = x(1:i); % Crop unused elements
y = y(1:i);

댓글 수: 2

Thanks for your help
i tried you advice
is it normal to take a long time to run?
What does "long" mean? Seconds or hours?
Symbolic calculations need some time. You can use the profiler to find the bottleneck:
doc profile

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

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

릴리스

R2021b

질문:

2022년 11월 19일

댓글:

Jan
2022년 11월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by