简单的MATLAB变量问题 [英] Simple MATLAB Variable Question
问题描述
请帮助我编写一个构造列矩阵 b 的MATLAB程序,例如
Please help me write a MATLAB program that constructs a column matrix b, such that
b 1 = 3x 1 -3/4y 0
b 2 = 3x 2
...
b n-2 = 3x n-2
b n-1 = 3x n-1 -3/4y n
b1 = 3x1 - 3/4y0
b2 = 3x2
...
bn-2 = 3xn-2
bn-1 = 3xn-1 - 3/4yn
其中 x 和 y 是变量.请注意, y 仅出现在 b 的第一和最后一个条目中.
where x and y are variables. Notice that y only appears in the first and last entries of b.
我的问题是我不知道变量如何在MATLAB中工作.我尝试过
My problem is that I don't know how variables work in MATLAB. I tried
b = 3 * x
b = 3*x
它说
???未定义的函数或变量"x"
??? Undefined function or variable 'x'
那么,我们如何创建变量而不是常量?
So, how do we create variables instead of constants?
谢谢!
推荐答案
根据上面的评论,您需要的是MATLAB的符号工具箱,该工具箱使您以变量的形式执行计算(而无需为其分配显式值).这是一个小例子:
From your comments above, what you need is MATLAB's symbolic toolbox, which allows you to perform computations in terms of variables (without assigning an explicit value to them). Here's a small example:
syms x %#declare x to be a symbolic variable
y=1+x;
z=expand(y^2)
z=
x^2 + 2*x + 1
有时需要使用expand
来获取多项式的完整形式,因为默认行为是将其保持为最简单的形式,即(1+x)^2
.这是找到一般二次方的根的另一个示例
You will need to use expand
sometimes to get the full form of the polynomial, because the default behaviour is to keep it in its simplest form, which is (1+x)^2
. Here's another example to find the roots of a general quadratic
syms a b c x
y=a*x^2+b*x+c;
solve(y)
ans =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
我认为您在最后一行中表示bn
和xn
...无论如何,这是您的操作方式:
I think you meant bn
and xn
in the last line... Anyway, here's how you do it:
b=3*x;
b([1,end])=b([1,end])-3/4*y([1,end])
您也可以像这样
b=3*x-3/4*[y(1); zeros(n-2,1); y(end)];
其中n
是向量的长度.
这篇关于简单的MATLAB变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!