[Content_Types].xml
_rels/.rels
matlab/document.xml
matlab/output.xml
metadata/coreProperties.xml
metadata/mwcoreProperties.xml
metadata/mwcorePropertiesExtension.xml
metadata/mwcorePropertiesReleaseInfo.xml
MATLAB Programming In this livescript, you will learn how to Use while loops in MATLAB to make repeated computations until a specified condition is met. Use conditional statements to distingush between cases. The While Loop We’ll begin by trying to solve the following linear equation numerically f(x)=x-2=0 Equation 1. Although we know the solution is x=2 , if f(x) were a more complicated function, it can be quite difficult to find the root and all we can then do is guess a solution. So, let’s begin by guessing a solution to Eq. (1), say x_{\text{guess}}=5 . We can verify that this is a poor guess by plugging it into the original equation f(x_{\text{guess}})=f(5)=5-2=3 But since we know that the solution is smaller than our guess, we can slowly lower our guessed value until we get the true solution. x_{i+1}=x_{i}-0.1 Equation 2. (a) Solve Eq. (1) using a for loop that implements Eq. (2). The problem here is that in general, we don’t really know when to stop the loop as the number of iterations required is dependent on the initial guess. Nonetheless, we do know that the iterate x will solve Eq. (1) if x_{i}-2=0 Equation 3. This is where a while loop is extremely helpful. It works by allowing the loop to run as long as a specified condition is (or is not) satisfied. In MATLAB, the structure of these loops is given by while condition instructions end Since we want the loop to run whenever Eq. (3) is not satisfied, we have the condition x_{i}-2\neq0 . Although in practice we will be unable to exactly determine the solution and as such we are interested in the solution to a specified tolerance |x_{i}-2|>\text{tol} Equation 4. So, using a while loop, a script that applies the root finding method defined by Eqs. (1) to (4) is given below. (a) Run \texttt{linear\_equation\_solver} in the section below. Is the result what you expect? %%%%%%%%%%%%%%%%%%%%%%%%%%
% linear_equation_solver %
%%%%%%%%%%%%%%%%%%%%%%%%%%
x = 5; % Initial Guess
tol = 10e-6; % Specified Tolerance
i = 1;
max_iter = 100; % Maximum number of iterations before the loops stops
while abs(x-2)>tol && i