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!