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

조회 수: 2 (최근 30일)
AVM
AVM 2020년 6월 7일
댓글: AVM 2020년 6월 9일
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')

채택된 답변

Walter Roberson
Walter Roberson 2020년 6월 8일
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
AVM
AVM 2020년 6월 9일
@walter: Thanks for your information. Now it's fine. There is no warning at all.

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

추가 답변 (1개)

Vishal Gaur
Vishal Gaur 2020년 6월 8일
편집: Vishal Gaur 2020년 6월 8일
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
AVM
AVM 2020년 6월 8일
편집: AVM 2020년 6월 8일
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.

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

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by