Indexing error while using symsum inside a function.
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2023-12-5
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 个评论
Walter Roberson
2023-12-5
编辑:Walter Roberson
2023-12-5
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!