2

I am trying to create a function in MATLAB which will expand a bracket to the power of n, where n is a natural number. This is what I have so far:

function expandb = expandb(x,y,n)
z = my_bincoeff1(n);;
syms v x y
v=1:n+1
for i=1:n+1
    v(i)=z(i)*x.^(n-i+1)*y.^(i-1);
end
a=0
for i=1+n+1
    a=a+v(i)
end

expandb = a;

I get this error when I run it:

??? The following error occurred converting from sym to double:
Error using ==> mupadmex
Error in MuPAD command: DOUBLE cannot convert the input expression into a double
array.
If the input expression contains a symbolic variable, use the VPA function instead.

Error in ==> expandb at 6
    v(i)=z(i)*x.^(n-i+1)*y.^(i-1);

So how do I store 2 variables in an array?

4

1 回答 1

1

问题在于,即使您首先使用SYMSv将其定义为符号对象,您仍将其重新定义为下一行的双精度值数组。然后,在循环的第一次迭代中,您索引的第一个元素并尝试在该元素中放置一个符号表达式。当 MATLAB 尝试将符号表达式转换为 double 类型以匹配数组的其他元素的类型时会出现错误(它不能这样做,因为表达式中有未指定的符号对象,如and )。vvxy

下面的解决方案应该完成你想要的:

function v = expandb(x,y,n)
  z = my_bincoeff1(n);
  syms v x y
  v = z(1)*x.^n;  %# Initialize v
  for i = 2:n+1
    v = v+z(i)*x.^(n-i+1)*y.^(i-1);  %# Add terms to v
  end
end
于 2010-12-12T20:56:16.423 回答