MATLAB: Solving linear equations with 2 unknown

linearstring

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

Best Answer

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;