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!