Stefan x
Stefan x

Reputation: 129

Sum with values from array in MATLAB

i have a question regarding sums in MATLAB using the symsum function.

enter image description here

I want to implement this function where ti is the i-th value from the array:

t={2, 5, 6, 10} as an example for n=4

and U is a symbolic variable.

is that somehow possible?

syms i, u
t={2, 5, 6, 10}    
symsum((u-i+1)*t{i},i,1,10);

Matlab then gives me the error:

Error using sym/subsindex (line 769)
Invalid indexing or function definition. When defining a function, ensure that the arguments are
symbolic variables and the body of the function is a SYM expression.

Can someone help me? Thanks in advance

Edit: Changed example formula

Upvotes: 0

Views: 181

Answers (1)

Nicky Mattsson
Nicky Mattsson

Reputation: 3052

You are mixing numerical calculations and symbolic calculations. Which is also written in the error message:

Function arguments must be symbolic variables, and function body must be sym expression.

t is not a symbolic expression, it is numerical (it only contain numbers). The solution is to align your method to either direction. In this case it means to the numerical version as symbolic indexing does not make sense.

Numerical

Use standard sum (this is also the fastest):

i = 1:4
syms U0
t = [2, 5, 6, 10];
f(U0) = sum((U0-i+1).*t);

Upvotes: 1

Related Questions