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

% 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

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

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

this code returns 14 terms, but the coefficient of each term is not really the individual element in vector c but the sum of all elements
c = [-1*ones(3,1); 0.3*ones(5,1); 0.6*ones(6,1)];
N = length(c);
k = (1:N).';
V = c./(1+r).^(k-1);
S_sum = sum(V);
After that you might want to simplify(S_sum)
now it works!!
I will look into what difference the following makes!
k = (1:N).';
Thank you so much!
+1 sir Walter but I don't understand why symsum produced 14 different vectors in this case ?
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.
Thank you very much ! sir Walter makes perfect sense.

Sign in to comment.

More Answers (1)

Tags

Community Treasure Hunt

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

Start Hunting!