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 Center および File ExchangeConversion 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