在 MATLAB 中求解二次方程
本教程将演示如何在 MATLAB 中求解二次方程。
在 MATLAB 中使用 solve()
方法求解二次方程
solve()
函数可以求解二次方程并为我们求根。它还可以求解高阶方程。让我们尝试使用 solve()
方法求解二次方程:
quad_equation1 = 'x^2 + 7*x + 10 = 0';
quad_equation2 = '7*x^2 + 5*x + 10 = 0';
X = solve(quad_equation1);
Y = solve(quad_equation2);
disp('The first root of the first quadratic equation is: '), disp(X(1));
disp('The second root of the first quadratic equation is: '), disp(X(2));
disp('The first root of the second quadratic equation is: '), disp(Y(1));
disp('The second root of the second quadratic equation is: '), disp(Y(2));
上面的代码尝试使用 solve()
方法求解两个给定的二次方程。
输出:
The first root of the first quadratic equation is:
-5
The second root of the first quadratic equation is:
-2
The first root of the second quadratic equation is:
- (255^(1/2)*1i)/14 - 5/14
The second root of the second quadratic equation is:
(255^(1/2)*1i)/14 - 5/14
在 MATLAB 中创建用户定义的函数来求解二次方程
我们可以创建函数来求解 MATLAB 中的二次方程。我们需要二次公式和二次方程的系数。
求解二次方程的函数将是:
function [x1, x2] = QuadraticEquation(a, b, c)
% quad. formula
d = b^2 - 4*a*c;
% the real numbered distinct roots
if d > 0
x1 = (-b+sqrt(d))/(2*a);
x2 = (-b-sqrt(d))/(2*a);
% the real numbered degenerate root
elseif d == 0
x1 = -b/(2*a);
x2 = NaN;
% complex roots will return NaN, NaN.
else
x1 = NaN;
x2 = NaN;
end
end
在上面的代码中,a
、b
和 c
是二次方程的系数,d
是二次公式。
现在,让我们尝试使用上面的函数求解二次方程。我们需要二次方程的系数作为输入。
例子:
[x1, x2] = QuadraticEquation (3, 4, -13)
[y1, y2] = QuadraticEquation (1,2,1)
[z1, z2] = QuadraticEquation (3, 3, 1)
输出:
x1 =
1.5191
x2 =
-2.8525
y1 =
-1
y2 =
NaN
z1 =
NaN
z2 =
NaN
相关文章
如何在 Matplotlib Pyplot 中显示网格
发布时间:2024/02/04 浏览次数:142 分类:Python
-
本文演示了如何在 Python Matplotlib 中在一个图上画一个网格。使用 grid()函数来绘制网格,并解释了如何改变网格颜色和线条类型。
在 Matplotlib 中的图中添加文字
发布时间:2024/02/04 浏览次数:180 分类:Python
-
本教程展示了我们如何使用 plt.text()方法在 Matplotlib 中为图或轴添加文字。
如何在 Matplotlib 中的多个线条之间进行填充
发布时间:2024/02/04 浏览次数:208 分类:Python
-
`fill_between()` 每次只能填充两条线之间的区域,但是我们可以选择一对行来填充多个线条之间的区域。
如何在 Matplotlib 中画一条任意线
发布时间:2024/02/04 浏览次数:166 分类:Python
-
本教程讲解了我们如何在 Matplotlib 中使用 matplotlib.pyplot.plot()、matplotlib.pyplot.vlines()、matplotlib.pyplot.hlines()方法和 matplotlib.collection.LineCollection 绘制任意线条。
Pandas 在 Matplotlib 柱状图上绘制多列图
发布时间:2024/02/04 浏览次数:189 分类:Python
-
在本教程中,我们将探讨如何使用 `DataFrame` 对象的 `plot()` 方法在柱状图上绘制多列。
如何在 Matplotlib 中绘制数据列表的直方图
发布时间:2024/02/04 浏览次数:178 分类:Python
-
本教程介绍了如何使用 plt.hist()方法从数据列表中绘制直方图。我们可以使用 plt.hist()方法从数据列表中绘制直方图。
Matplotlib 中的叠加条形图
发布时间:2024/02/04 浏览次数:182 分类:Python
-
本教程展示了如何使用 plt.bar()方法将某些数据集的条形图堆叠在另一个数据集上。我们在 Matplotlib 中使用 matplotlib.pyplot.bar()方法生成条形图。
在 Python Matplotlib 中生成反向色彩图
发布时间:2024/02/04 浏览次数:136 分类:Python
-
本教程解释了如何反转 Python Matplotlib Plot 的 Colormap。
设置 Matplotlib 网格间隔
发布时间:2024/02/04 浏览次数:250 分类:Python
-
本教程将介绍我们如何在 Matplotlib 绘图中设置网格间距,并对主要网格和次要网格应用不同的样式。