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

1 回表示 (過去 30 日間)
Yihan Hu
Yihan Hu 2018 年 12 月 7 日
コメント済み: madhan ravi 2018 年 12 月 8 日
% 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 Center および File ExchangeNumbers and Precision についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by