Solving linear equations with 2 unknown

9 views (last 30 days)
Hello
I need some help to use text/string inside my function
I want to make a function that can solve 2 linear equations with 2 unknonws. At this moment my function inside my m. file looks like this (just below). But instead of (a1,b1,a2,b2) I want to write whole equations: Loesligninger('y=2x+1','y=3x-2'), and return a result like this:'x=3,y=7'
function s=LoesLigninger(a1,b1,a2,b2)
A=[-a1,1;-a2,1];
b=[b1;b2];
s=A\b;
s=inv(A)*b;
end

Accepted Answer

Star Strider
Star Strider on 22 Aug 2015
You can write the equations easily enough by adding this line to the function or to your script after calling the function:
sprintf('y = %.2fx %+.2f', s)
If you want to add ‘x’ as an argument or specify it in your calling script, you can calculate and display ‘y’ as:
yf = @(s,x) s(1).*x + s(2);
sprintf('x = %.2f, y = %.2f', x, yf)
Use fprintf if you want to display to the Command Window, and sprintf if you want to save the string to output somewhere else.
Also, this line isn’t necessary:
s=inv(A)*b;
  10 Comments
Walter Roberson
Walter Roberson on 24 Aug 2015
function s=LoesLigninger1(a1,b1,a2,b2)
A=[-a1,1;-a2,1];
b=[b1;b2];
s=A\b;
fprintf('\n\tx = % .2f, y = % .2f\n', s);
Mathias Eriksen
Mathias Eriksen on 24 Aug 2015
Thank you both, with yours help it works now. The part where I need to write the function LoesLigninger('y=2x+1','y=3x-2') is not important as the return of x=3,y=7 (thumps up)

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 22 Aug 2015
In order to be able to pass the equations in as strings, you need to define the permitted syntaxes. For example do you need to be able to call,
LoesLigninger2('y is ummm, three g plus pi','let y be, I don''t know, say five more than twice the other variable maybe? What about that?')
Even if you restrict yourself to 'x' and 'y', you need to define whether multiplication by 1 needs to written in, and you need to define whether addition or subtraction of 0 needs to be written in, and you need to know about allowed spacing and about whether tabs are allowed. Is 'y = x' to be allowed or would it have to be written as 'y=1x+0' ? Are fractions to be allowed? Is floating point to be allowed? Is the imaginary unit sqrt(-1) to be represented by "i" or by "I" or by "j" ? When the constant multiples are being formed is it allowed to specify them as (for example) "sqrt(2)" ? Are negative multiples allowed? Can the user use brackets? Can the user use "unary plus" and "unary minus" such as in 'y=+3x+-7' ?
The more flexibility you allow, the harder it is to parse. If you restrict the flexibility a lot it might be easy to process.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!