Please help me write a MATLAB program that constructs a column matrix b, such that
b1 = 3x1 - 3/4y0
b2 = 3x2 ... bn-2 = 3xn-2 bn-1 = 3xn-1 - 3/4yn
where x and y are variables. Notice that y only appears in the first and last entries of b.
My problem is that I don't know ho开发者_StackOverflow中文版w variables work in MATLAB. I tried
b = 3*x
and it says
??? Undefined function or variable 'x'
So, how do we create variables instead of constants?
Thanks!
EDIT:
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
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)
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])
You can also do it in a single line as
b=3*x-3/4*[y(1); zeros(n-2,1); y(end)];
where n
is the length of your vector.
You never stated your problem...
Anyways just set the first entry of b individually first. Then use a loop to set the next values of b from 2 up to n-2. Then set the last entry of b individually.
On a side note, if x is a vector, you can simply vectorize the loop part.
精彩评论