How to form a function using 'for loop' without 'sym' command
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Jan
le 6 Sep 2021
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.
Réponses (2)
Abolfazl Chaman Motlagh
le 6 Sep 2021
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 commentaires
Walter Roberson
le 6 Sep 2021
syms is an abbreviation for sym() so this does not satisfy the requirement to not use sym
Walter Roberson
le 6 Sep 2021
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 commentaires
Walter Roberson
le 7 Sep 2021
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))
Voir également
Catégories
En savoir plus sur Calculus dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!