How to form a function using 'for loop' without 'sym' command
1 回表示 (過去 30 日間)
古いコメントを表示
i tried like this
m = 150;
Aos = 40;
nAi = 0;
for i=1:2:m
nAi = @(phi)nAi+cos(i*phi);
end
nA = vpa((nAi+Aos), 4)
Iam getting this error
Operator '+' is not supported for operands of type 'function_handle'.
Error in ll (line 8)
nA = vpa(nAi+Aos, 4)
2 件のコメント
Jan
2021 年 9 月 6 日
You did not mention, what you try to achieve. All we see is the failing code. This is not enough information to guess, what you want to get instead.
回答 (2 件)
Abolfazl Chaman Motlagh
2021 年 9 月 6 日
Assuming you want nA be function of phi, you can use symsum for summuation :
m = 150;
Aos = 40;
syms phi k
nAi =@(phi) symsum(cos(2*k*phi),k,1,m/2);
nA =@(phi) vpa((nAi(phi)+Aos), 4);
% example
nA(pi)
2 件のコメント
Walter Roberson
2021 年 9 月 6 日
syms is an abbreviation for sym() so this does not satisfy the requirement to not use sym
Walter Roberson
2021 年 9 月 6 日
m = 150;
Aos = 40;
nAi = @(phi) zeros(size(phi));
for i=1:2:m
nAi = @(phi)nAi(phi)+cos(i*phi);
end
nA = @(phi) nAi(phi)+Aos
You asked to avoid sym, so it seems likely to me you want to avoid using vpa() as well. But if using a final vpa is okay, then
vpa(nA, 4)
2 件のコメント
Walter Roberson
2021 年 9 月 7 日
With vpa(), the symbol for phi appears if you are using LiveScript, but not for traditional .m files.
To get the result without using vpa:
m = 150;
Aos = 40;
nA = str2func("@(phi) " + strjoin(compose("cos(%d*theta)", 1:2:m), " + ") + " + " + string(Aos))
参考
カテゴリ
Help Center および File Exchange で Calculus についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!