数组中有2个变量

发布于 2024-10-07 01:30:07 字数 663 浏览 0 评论 0 原文

我正在尝试在 MATLAB 中创建一个函数,它将括号展开为 n 次方,其中 n 是自然数。这是我到目前为止所得到的:

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;

运行时出现此错误:

??? 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);

那么如何在数组中存储 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

护你周全 2024-10-14 01:30:07

问题在于,即使您首先使用 v 定义为符号对象rel="nofollow">SYMS,您将其重新定义为下一行的双精度值数组。然后,在循环的第一次迭代中,您索引 v 的第一个元素,并尝试在该元素中放置符号表达式。当 MATLAB 尝试将符号表达式转换为 double 类型以匹配数组 v 的其他元素的类型时,会出现错误(它无法执行此操作,因为存在未指定的符号对象,例如 表达式中的 xy)。

下面的解决方案应该可以实现您想要的:

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

The problem is the fact that, even though you first define v as a symbolic object using SYMS, you redefine it to be an array of double values on the next line. Then, in the first iteration of your loop you index the first element of v and try to place a symbolic expression in that element. The error arises when MATLAB tries to convert the symbolic expression to type double to match the type of the other elements of the array v (which it can't do because there are unspecified symbolic objects like x and y in the expression).

The solution below should accomplish what you want:

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文