简体   繁体   中英

Solving a system of linear equations in matlab using coefficients supplied at run time

I am trying to solve a system of linear equations in matlab; the coefficients of the equations are to be supplied by the user at run time. Problem is that the solution is given by matlab as symbolic variables and I am unable to convert them to human-readable formats like double. My Scripts:

% Accept coefficient of x in eqn one
a11 =input('Enter coefficient of x eqn one:');
%Accept coeff of y in eqn one
a12 = input('Enter coefficient of y in eqn one: ');
%Accept the constant term of eqn one
c1 = input('Enter the constant term  in eqn one:');
%Form eqn one
eqn1 =sym( 'a11*x + a12*y + c1');
eqn_one = subs(eqn1, {a11, a12, c1},{a11, a12, c1})
a21 = input('Enter coefficient of x in eqn two:');
a22 = input('Enter coefficient of y in eqn two:');
c2 = input('Enter the constant term in eqn two:');
eqn2 = sym( 'a21*x + a22*y + c2');

eqn_two = subs(eqn2, {a21, a22, c2},{a21, a22, c2})
solve(eqn_one, eqn_two)

This is matlab's result:

ans =

x: [1x1 sym]
y: [1x1 sym]

You have to save the results:

[x,y] = solve(eqn_one, eqn_two);

and then (if you terminated the line with ';')

display(x);display(y);

Or, if you want numeric expressions use the documentation to find:

disp(eval(x));disp(eval(y));

However as pointed out solve or roots or similar functions can do the same without symbolic math. This is way better, since maltab is really unhandy when it comes to symbols.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM