Today two of my juniors came to me for a simple MATLAB term project. It's quite an easy project but i thought to share it for those students who are dealing with basics of MATLAB. Mostly such projects are offered to students in first or second semester when they have very basic knowledge of MATLAB coding and they feel helpless while solving such problems as is the case with those two students. So, let's get started with How to find Roots of Quadratic Equations in MATLAB.
%==== Code Starts Here(www.TheEngineeringProjects.com) ==== clc clf % ============ Taking Inputs From User ============== handle = input('Enter the handle of the function : '); limit = input('Enter the domain limits : '); initial = input('Enter the initial solution estimate : '); k = input('Enter 1 for min, 2 for roots & 3 for both : '); syms x; a1 = 100000; %====== Calculating Roots of the Quadratic Equation ========= func = @(x)handle(1,1)*x^2 + handle(1,2)*x + handle(1,3); root1 = (-handle(1,2) + sqrt((handle(1,2)^2)-(4*handle(1,1)*handle(1,3))))/(2*handle(1,1)); root2 = (-handle(1,2) - sqrt((handle(1,2)^2)-(4*handle(1,1)*handle(1,3))))/(2*handle(1,1)); roots=[root1,root2]; %====== Calculating Minimum Value Within Domain Limits ========= for x = limit(1,1):0.1:limit(1,2) a = func(x); if (a < a1) a1 = a; x1 = x; end if(k==1 || k==3) plot(x,a,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g',... 'MarkerSize',10) hold on; end end min = a1; %====== Displaying Roots & Minimum Values ========= if ( k == 1) min end if ( k == 2) roots plot(x,root1,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','r',... 'MarkerSize',10) hold on; plot(x,root2,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','r',... 'MarkerSize',10) end if ( k == 3) min roots plot(x,root1,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','r',... 'MarkerSize',10) hold on; plot(x,root2,'--rs','LineWidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','r',... 'MarkerSize',10) end %==== Code Ends Here(www.TheEngineeringProjects.com) =======
- First input = [1 5 6]
- Second input = [-1 1]
- Third input = 0
- Fourth input = 3