How to use fzero function in Matlab/Octave?
Overview
Let’s discuss the usage of the Matlab function fzero function and how to use it in scripts. We can use the function to find the roots of the problem or values of the variable where the function tends to zero.
Consider the below function:
The problem of root finding is such that :
xRoot is the root of the function. In some cases we may want to approximate and find an approximate root value under given tolerance tol value.
Problem
Let’s consider a small problem and develop a script to find the solution.( Based on Angry Birds Game)
Assume a Pig is at the coordinates ( 100,25). We need to shoot an angry bird to hit the pig. The initial velocity of the bird is 60 m/s. The gravity constant is 9.81. y can be calculated as per the formula:
;
fzero function
root = fzero(@(theta0) f(theta0), [45 90]);
To know more information on fzero, browse the help documentation. To get the help, type the following in the command window prompt.
>> help fzero
In the script we have two initial guesses within two intervals. 0 -45 degrees and another in the interval 45 – 90 degrees.
MATLAB/Octave Script
% Projectile of Angry Bird %Intial Velocity v0=60; %Gravity constant g=9.81; %Pig location xPig=100; %Pig y location yPig=25; f = @(theta) xPig*tan(theta*pi/ 180) - (0.5*xPig^2*g)/(v0^2*cos(theta*pi/180)^2)- yPig thetaRoot1 = fzero(@(theta0) f(theta0), [0 45]); fprintf('Theta Root 1:= %4.2f degrees \n', thetaRoot1); thetaRoot2 = fzero(@(theta0) f(theta0), [45 90]); fprintf('Theta Root 2:= %4.2f degrees \n', thetaRoot2); xPoints1= linspace(0,100,100); yPoints1= xPoints1.*tan(thetaRoot1.*pi/ 180) - (0.5.*xPoints1.^2.*g)/(v0.^2.*cos(thetaRoot1.*pi/180)^2); xPoints2= linspace(0,100,100); yPoints2= xPoints2.*tan(thetaRoot2.*pi/ 180) - (0.5.*xPoints2.^2.*g)/(v0.^2.*cos(thetaRoot2.*pi/180)^2); figure hold on grid off plot(xPoints1,yPoints1,':bo','LineWidth',7.0,... 'MarkerEdgeColor','g',... 'MarkerFaceColor','r',... 'MarkerSize',30) plot(xPoints2,yPoints2,':ro','LineWidth',7.0,... 'MarkerEdgeColor','b',... 'MarkerFaceColor','k',... 'MarkerSize',30) xlabel('x') ylabel('y') title('Angry bird vs Pig')
Roots:
Run the script in the MATLAB or Octave command prompt window.
>> AngryBird
Theta Root 1:= 22.25 degrees
Theta Root 2:= 81.79 degrees
Screenshot
The script plots the trajectory of the angry bird with two blue and green markers as shown below:
Octave Tutorial on this website can be found at:
https://www.testingdocs.com/octave-tutorial/
More information on Octave can be found on the official website:
https://www.gnu.org/software/octave/index