Use sym to define a sum function, but i have a problem with indexing

조회 수: 1 (최근 30일)
% Define N(r)
c = [-1*ones(3,1); 0.3*ones(5,1); 0.6*ones(6,1)];
n = length(c);
syms k r
f = c(k)/(1+r)^(k-1);
V = subs(f, k, 1:n);
S_sum = sum(V);
Apparently Matlab gives me this problem when I tried to use elements in array c, e.g. c(1) to c(k)
Error using sym/subsindex (line 836)
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments
must be symbolic variables, and function body must be sym expression.
How should I fix this index problem?
Thank you!
  댓글 수: 1
Yihan Hu
Yihan Hu 2018년 12월 8일
so I tried a different approach still using sym but it is a bit labor
c = [-1*ones(3,1); 0.3*ones(5,1); 0.6*ones(6,1)];
n = length(c);
syms N(r)
N(r) = c(1)/(1+r)^(1-1)+c(2)/(1+r)^(2-1)+c(3)/(1+r)^(3-1)+c(4)/(1+r)^(4-1)...
+c(5)/(1+r)^(5-1)+c(6)/(1+r)^(6-1)+c(7)/(1+r)^(7-1)+c(8)/(1+r)^(8-1)+...
c(9)/(1+r)^(9-1)+c(10)/(1+r)^(10-1)+c(11)/(1+r)^(11-1)+c(12)/(1+r)^(12-1)...
+c(13)/(1+r)^(13-1)+c(14)/(1+r)^(14-1);
the following answers don't really give what I want here

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

채택된 답변

Walter Roberson
Walter Roberson 2018년 12월 8일
it is never permitted to use aa symbolic variable as a subscript , not even for symsum.
You need to construct the definite equation
k = 1:N;
V = c./(1+r).^(k-1);
S_sum = sum(V);
  댓글 수: 6
Walter Roberson
Walter Roberson 2018년 12월 8일
c is a column vector but k was a row vector, ./ was doing the equivalent of bsxfun(@divide, column_vector_expression, row_vector_expression) and so producing a 2D array.
madhan ravi
madhan ravi 2018년 12월 8일
Thank you very much ! sir Walter makes perfect sense.

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

추가 답변 (1개)

madhan ravi
madhan ravi 2018년 12월 8일
syms r
k=1:n;
f = c(k)./(1+r).^(k-1);
S_sum=vpa(symsum(f),2);

카테고리

Help CenterFile Exchange에서 Numbers and Precision에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by