question about solving system of equations using symbolic math

左心房为你撑大大i 提交于 2019-12-25 01:14:52

问题


I want to use symbolic symbol to solve a system of linear equation. So I prepare the following code.

A=[1,2;3,4];

% syms x
x=sym('x_%d',[2 1]);

eqn=A*x==[1;2];

result=solve(eqn,x)

Interestingly, it works, but when I read the variable result, it gives a 1X1 struct with x_1 and x_2 are 1X1 sym. But what I expect get should be 2 real values, why? Could someone explain it? Remark: do not want to use A^-1*[1;2] to obtain the answer.


回答1:


  • If you set the output to single variable solve returns a structure data type that contains all the solutions, to get each solution use the dot. assignment, like result.x_1 or result.x_2

The code is as follows

A=[1,2;3,4];

% syms x
x=sym('x_%d',[2 1]);

 eqn=A*x==[1;2];
result = solve(eqn,x);
result.x_1
% 0
result.x_2
% 1/2

  • If you want to have result as an array, use multiple output format, like result(1) for the first variable, result(2) for the second variable

The code is as follows

A=[1,2;3,4];

% syms x
x=sym('x_%d',[2 1]);

 eqn=A*x==[1;2];

[result(1), result(2)] = solve(eqn,x);
result
% result = [0 , 1/2]


来源:https://stackoverflow.com/questions/56682126/question-about-solving-system-of-equations-using-symbolic-math

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!