I am trying to implement the following double summation in a function:
f(x,y)=\\sum_{k=0}^{S}\\sum_{l=0}^{S}{a_{kl}x^ky^l}
.
Here is my first attempt:
function [ a ] = MyFun( S )
a=randi([0 9],S+1);
syms x y k l;
f(x,y)=symsum(symsum(a(k,l)*x^k*y^l,l,1,S+1),k,1,S+1);
f(1,2)
end
Actually, my code evaluates f
in a loop later on, but that does not seem relevant here. Trying something like MyFun(3)
results in an error:
Error using sym/subsindex (line 766) 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. When indexing, the input must be numeric, logical, or ':'.
Error in MyFun (line 4) f(x,y)=symsum(symsum(a(k,l)*x^(k-1)*y^(l-1),l,1,S+1),k,1,S+1);
Everything works fine if a(k,l)*
is removed from the inner symsum
, so I suspect that there is something wrong with the indices. Is it not possible to use the symbolical variables k
and l
as indices? If not, how can I solve this?
Indexing a matrix using a symbolic value does not seem to work. As an alternative you can use elementwise multiplication as follows:
function f = MyFun( S )
a=randi([0 9],S+1);
k = repmat((0:S)', 1, S+1);
l = repmat((0:S), S+1, 1);
syms x y;
f(x, y) = sum(sum(a .* x.^k .* y.^l));
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.