Why does my anonymous function give array indices error?

조회 수: 5 (최근 30일)
Ann
Ann 2024년 10월 16일
답변: Ann 2024년 10월 17일
I am trying to make a function that inputs no. of terms and calculates a fourier series to that many terms. To do this I am using a for loop to update an anonymous function to add each term.
apprxf = @(x) a0/2;
for n = 1:terms
apprxf = @(x) apprxf(x) + a(x)*cos(n*x) + b(x)*sin(n*x);
end
When I try to plot the function "apprxf", or just input any non integer (such as apprxf(pi) ), I get the error message saying:
"Array indices must be positive integers or logical values." and then points to what is line 4 here.
Does Matlab see the anonymous function as an array instead? There is nothing in the workspace to indicate that there is one that's overriding it, but maybe there still is.
How can I fix this in a way that allows me to plot this function as a graph from 0 to 2pi.
  댓글 수: 2
Torsten
Torsten 2024년 10월 16일
편집: Torsten 2024년 10월 16일
Where do you define a and b as functions of x ?
And if you want to evaluate "apprxf" for x being an array, you'll probably need pointwise operations:
apprxf = @(x) apprxf(x) + a(x).*cos(n*x) + b(x).*sin(n*x);
instead of
apprxf = @(x) apprxf(x) + a(x)*cos(n*x) + b(x)*sin(n*x);
Walter Roberson
Walter Roberson 2024년 10월 17일
apprxf = @(x) apprxf(x) + a(x)*cos(n*x) + b(x)*sin(n*x);
when the input x is pi then that would be apprxf(pi) + a(pi)*cos(n*pi) + b(pi)*sin(n*pi)
If a and b are arrays, then that would be an attempt to index array a at location pi

댓글을 달려면 로그인하십시오.

채택된 답변

Ann
Ann 2024년 10월 17일
The answer to this was in fact that I didn't check through my code properly. It should have been "apprxf = @(x) apprxf(x) + a(n)*cos(n*x) + b(n)*sin(n*x);" Instead of "apprxf = @(x) apprxf(x) + a(x)*cos(n*x) + b(x)*sin(n*x);" As the comments pointed out, inputting a non integer attempts to read from a non integer index in arrays a and b, when in reality those should have been using n.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by