如何在双符号和中使用矩阵项? [英] How to use matrix entries in a double symsum?
问题描述
我正在尝试在函数中实现以下双重求和:
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}
.
这是我的第一次尝试:
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
实际上,我的代码稍后会在循环中对f
进行求值,但这在这里似乎无关紧要.尝试类似MyFun(3)
的操作会导致错误:
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:
使用sym/subsindex时出错(第766行)无效的索引编制或函数 定义.定义函数时,请确保参数为 符号变量和函数的主体是SYM表达式. 编制索引时,输入必须为数字,逻辑或:".
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 ':'.
MyFun中的错误(第4行) f(x,y)=符号(symsum(a(k,l)* x ^(k-1)* y ^(l-1),l,1,S + 1),k,1,S + 1 );
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);
如果从内部symsum
中删除了a(k,l)*
,则一切正常,因此我怀疑索引有问题.不能将符号变量k
和l
用作索引吗?如果没有,我该如何解决?
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
这篇关于如何在双符号和中使用矩阵项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!