How to form a function using 'for loop' without 'sym' command
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Jan
el 6 de Sept. de 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.
Respuestas (2)
Abolfazl Chaman Motlagh
el 6 de Sept. de 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 comentarios
Walter Roberson
el 6 de Sept. de 2021
syms is an abbreviation for sym() so this does not satisfy the requirement to not use sym
Abolfazl Chaman Motlagh
el 6 de Sept. de 2021
Oh! sorry, i just read the content not title of question.
Walter Roberson
el 6 de Sept. de 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 comentarios
Walter Roberson
el 7 de Sept. de 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))
Ver también
Categorías
Más información sobre Calculus en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!