problem in variable pre-allocation in ''For Loop''

2 views (last 30 days)
I would like to run a ''for loop'' and I am illustrating this in my code. But It is always showing some message the '' the Variable ''Hpn" and ''Hmn '' appears to change size on every loop iteration (within a script). Consider preallocating for speed". what does it mean? How do can I fix this issue for better performance the matlab. Pl somebody help me.
clc;
syms n m theta r
mu=0.2;
nu=0.1;
guard_digits = 10;
theta=0:0.1:2*pi;
f=zeros(size(theta));
for i=1:length(theta)
beta=r.*exp(1i.*theta(i));
Hpn(n,m)=(((-1).^(n))./(pi.*mu.*sqrt(factorial(n).*factorial(m)))).*((-nu./(2.*mu)).^((n+m)./2));
Hmn (n,m)=(((-1).^(m))./(pi.*mu.*sqrt(factorial(m).*factorial(n)))).*((-nu./(2.*mu)).^((n-m)./2));
Hp=Hpn(1,n-1)+Hmn(0,m);
Hm= Hpn(0,m-1)-Hmn(n+1,m);
H1=sum(vpa(subs(Hp,m,1:6), guard_digits));
H2=sum(vpa(subs(Hm,m,1:6), guard_digits));
H=H1+H2;
h=sum(vpa(subs(H,n,1:6), guard_digits));
fun=r.*h;
F = matlabFunction(fun);
f(i)= integral(@(r) F(r),0,5);
end
polarplot(theta, f,'b')

Accepted Answer

Walter Roberson
Walter Roberson on 8 Jun 2020
MATLAB is getting confused in its warnings when you keep redefining the symbolic functions Hpn and Hmn . You can get rid of that warning by substituting
Hpn = symfun( (((-1).^(n))./(pi.*mu.*sqrt(factorial(n).*factorial(m)))).*((-nu./(2.*mu)).^((n+m)./2)), [n, m]);
Hmn = symfun( (((-1).^(m))./(pi.*mu.*sqrt(factorial(m).*factorial(n)))).*((-nu./(2.*mu)).^((n-m)./2)), [n m]);
  1 Comment
AVM
AVM on 9 Jun 2020
@walter: Thanks for your information. Now it's fine. There is no warning at all.

Sign in to comment.

More Answers (1)

Vishal Gaur
Vishal Gaur on 8 Jun 2020
Edited: Vishal Gaur on 8 Jun 2020
There is no problem with your code and note that it is a warning, not an error. This warning may lead to less efficiency in terms of running time for larger values, but it will not affect your answer. So, if you are working for small values, you can ignore this warning. But in case of larger values, you may get a major slowdown.
You can try to pre-allocate the variables hpn, hmn by some value before the loop, if you are aware of them.
You can have a look here for more information about the performance of the incremental growth of array.
  1 Comment
AVM
AVM on 8 Jun 2020
Edited: AVM on 8 Jun 2020
Thanks for your information. One thing that I would like to know that if Hpn(n,m) and Hmn(n,m) are functions of symbolic variable i.e."n","m" and "beta"(in case of more complicated function) then how do I can preallocate them? Moreover where to place that preallocated Hpn and Hmn inside the " for loop" or outside the loop. Pl let me know.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!