MATLAB程序问题
syms x y z t a b c d m s;
f = x+z-a;
g = (2^(1/2)*m*x)/2 + (2^(1/2)*m*y)/2+(2^(1/2)*m*t)/2 - (2^(1/2)*m*z)/2-b;
h = m^2*(y- t)-m^2*c;
k = (2^(1/2)*m^3*(y-x+z+t))/2-m^2*d;
[x,y,z,t] = solve(f,g,h,k);
x = simplify(x),
y = simplify(y),
z = simplify(z),
t = simplify(t)
得到的答案
x =
(2^(1/2)*(b + d))/(4*m) - c/2
y =
a/2 + (2^(1/2)*(b - d))/(4*m)
z =
c/2 + (2^(1/2)*(b + d))/(4*m)
t =
a/2 - (2^(1/2)*(b - d))/(4*m)
但是这个答案有问题,将x,z带入f方程,明显不成立,运行给的这个答案把x,y 的值和z,t的对调了。求教原因? 展开
楼上的回答存在问题。
诚然,Mathematica在符号运算方面总体上优于MATLAB,推荐使用Mathematica没问题;但楼上关于MATLAB符号运算的说法却纯粹是想当然,像这样误导人的做法以后还是应该少一些。
其实,当solve返回多个输出参数的时候,其顺序是按照字母表顺序,而不是你通过输入参数指定的变量顺序,也不是楼上所说的【按照变量出现的先后顺序】。所以不小心很容易搞错(对于当前这个例子没问题)。
从solve函数的说明中摘录一段:
>> help solve
SOLVE Symbolic solution of algebraic equations.
......
Three different types of output are possible. For one equation and one
output, the resulting solution is returned, with multiple solutions to
a nonlinear equation in a symbolic vector. For several equations and
an equal number of outputs, the results are sorted in lexicographic
order and assigned to the outputs. For several equations and a single
output, a structure containing the solutions is returned.
现在应该明白怎么做了吧?调用时应该是
[t,x,y,z] = solve(f,g,h,k);
再检验一下结果看看:
f=simple(subs(f))
g=simple(subs(g))
h=simple(subs(h))
k=simple(subs(k))
f =
0
g =
0
h =
0
k =
0
比 较好的做法是返回一个输出参数,该参数为结构体,然后再获得结构体的域即可:
s=solve(....);
fns = fieldnames(s);
for i=1:length(fns)
eval([fns{i} '=s.' fns{i}]);
end
在MATLAB中同样也可以用一个命令解决:
>> s=solve('x+z-a', '(2^(1/2)*m*x)/2 + (2^(1/2)*m*y)/2+(2^(1/2)*m*t)/2 - (2^(1/2)*m*z)/2-b', 'm^2*(y- t)-m^2*c', '(2^(1/2)*m^3*(y-x+z+t))/2-m^2*d')
s =
t: [1x1 sym]
x: [1x1 sym]
y: [1x1 sym]
z: [1x1 sym]
后面用s.t、s.x之类的符号就可以引用求得的结果了。
[x,y,z,t]=solve(...)
返回的x,y,z,t不是按照方程里的变量名来赋值,而是按照变量出现的先后顺序赋值,所以结果里运行给的这个答案把x,y 的值和z,t的对调了
我还是不太明白,按照出现顺序应该是x,z,y,t,那应该怎么样才是对的呢
按照matlab的语法可以这样写,[x,y,z,t]=solve('f','g','h','k','x','y','z','t');
但这样写之后matlab的符号计算能力就不足以计算出来了~~
推荐你使用mathematica,符号计算能力超强~~
只需一条语句,Solve[-a + x + z ==
0 && -b + (m t)/Sqrt[2] + (m x)/Sqrt[2] + (m y)/Sqrt[2] - (m z)/
Sqrt[2] == 0 && -c m^2 + m^2 (-t + y) ==
0 && -d m^2 + (m^3 (t - x + y + z))/Sqrt[2] == 0, {x, y, z, t}]
得到结果
{{x -> -((-Sqrt[2] b + Sqrt[2] d - 2 a m)/(4 m)),
y -> c/2 + b/(2 Sqrt[2] m) + d/(2 Sqrt[2] m),
z -> a/2 - b/(2 Sqrt[2] m) + d/(2 Sqrt[2] m),
t -> -(c/2) + b/(2 Sqrt[2] m) + d/(2 Sqrt[2] m)}}
广告 您可能关注的内容 |