Indexing error while using symsum inside a function.
2 views (last 30 days)
Show older comments
Does anyone know why I am recieving the indexing error below?
x = 0:0.01:5
y = [2 -1 3 -2 4 -3 2 -4 1 -2]
Test(x,y)
function f = Test(x,y)
syms k
f = symsum(y(k)*sin(2*pi*k*x),k,1,size(y));
end
2 Comments
Accepted Answer
Walter Roberson
on 5 Dec 2023
y = [2 -1 3 -2 4 -3 2 -4 1 -2]
Your y is a numeric vector.
Test(x,y)
you are passing that numeric vector as the second parameter to Test
function f = Test(x,y)
Internally, Test knows that numeric vector under the name y
syms k
f = symsum(y(k)*sin(2*pi*k*x),k,1,size(y));
You try to index that numeric vector with a symbolic variable. In MATLAB, you can never index an array at a symbolic variable.
What you need to do is
function f = Test(x,y)
f = sum(y.*sin(2*pi*(1:numel(y)).*x));
end
That is, form a definite list of terms and sum() them.
2 Comments
Walter Roberson
on 5 Dec 2023
Edited: Walter Roberson
on 5 Dec 2023
x = 0:0.01:5
y = [2 -1 3 -2 4 -3 2 -4 1 -2]
z = Test(x,y)
plot(x, z)
function f = Test(x,y)
f = sum(y(:).*sin(2*pi*(1:numel(y)).'.*x),1);
end
More Answers (0)
See Also
Categories
Find more on Calculus in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!