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

1 view (last 30 days)
% 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 Comment
Yihan Hu
Yihan Hu on 8 Dec 2018
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

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Dec 2018
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 Comments
Walter Roberson
Walter Roberson on 8 Dec 2018
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.

Sign in to comment.

More Answers (1)

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

Tags

Community Treasure Hunt

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

Start Hunting!