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!