迎 eg. a=[135]; >>c C= b=[123]; 1615 的 >>[lastmsg,lastid]=lasterr c=a.*b' lastmsg catch Error using=>times c=a.*b; Matrix dimensions must agree. lastid end MATLAB:dimagree 26
26 eg. a=[1 3 5]; b=[1 2 3]; try c=a.*b' catch c=a.*b; end >> c c = 1 6 15 >> [lastmsg,lastid]=lasterr lastmsg = Error using ==> times Matrix dimensions must agree. lastid = MATLAB:dimagree
② eg. a=[123] a= b=[456] 123 try c-a*b; disp('try is excute') b= catch 456 c=a.*b; catch is excute disp('catch is excute') end 27
27 eg. a=[1 2 3] b=[4 5 6] try c=a*b; disp('try is excute') catch c=a.*b; disp('catch is excute') end a = 1 2 3 b = 4 5 6 catch is excute
例:求解一元二次方程 ■方程式:x2+bx+C=0 ■求解过程: ■1)通过键盘输入系数; ■2)计算方程根; ■3)输出方程根。 28
28 例:求解一元二次方程 方程式:ax2 + bx + c = 0 求解过程: 1)通过键盘输入系数; 2)计算方程根; 3)输出方程根
花 MATLAB程序: Script file:calc roots.m Purpose: This program solves for the roots of a quadratic equation. of the form a*x 2+b*x+c=0.It calculates the answers ■% regardless of the type of roots that the equation possesses. Record of revisions: Date Programmer Description of change ■% 12/04/98 S.J.Chapman original code ■%Define variables: ■ a--Coefficient of x 2 term of equation b--Coefficient of x term of equation c--Constant term of equation discriminant--Discriminant of the equation ■% imag-part--Imag part of equation (for complex roots) real part--Real part of equation (for complex roots) x1--First solution of equation (for real roots) x2--Second solution of equation (for real roots) 29
29 MATLAB 程序: % Script file: calc_roots.m % Purpose: % This program solves for the roots of a quadratic equation. % of the form a*x^2 + b*x + c = 0. It calculates the answers % regardless of the type of roots that the equation possesses. % Record of revisions: % Date Programmer Description of change % 12/04/98 S. J. Chapman original code % Define variables: % a -- Coefficient of x^2 term of equation % b -- Coefficient of x term of equation % c -- Constant term of equation % discriminant -- Discriminant of the equation % imag-part -- Imag part of equation (for complex roots) % real_part -- Real part of equation (for complex roots) % x1 -- First solution of equation (for real roots) % x2 -- Second solution of equation (for real roots)
迎 Prompt the user for the coefficients of the equation disp ('This program solves for the roots of a quadratic'); disp ('equation of the form A*X2+B*X+C=0.) a=input ('Enter the coefficient A:') b=input('Enter the coefficient B:') c=input ('Enter the coefficient C:) Calculate discriminant discriminant =b2-4 a c; 30
30 % Prompt the user for the coefficients of the equation disp ('This program solves for the roots of a quadratic’); disp ('equation of the form A*X^2 + B*X + C = 0. '); a = input ('Enter the coefficient A: '); b = input ('Enter the coefficient B: '); c = input ('Enter the coefficient C: '); % Calculate discriminant discriminant = b^2 - 4 * a * c;