Solving linear equations with 2 unknown

조회 수: 9 (최근 30일)
Mathias Eriksen
Mathias Eriksen 2015년 8월 22일
댓글: Mathias Eriksen 2015년 8월 24일
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

채택된 답변

Star Strider
Star Strider 2015년 8월 22일
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
Walter Roberson
Walter Roberson 2015년 8월 24일
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 2015년 8월 24일
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)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2015년 8월 22일
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!

Translated by