5The programming environmentMatlab can’t tell if identifier is variable or function>> z=theta;Matlab searches for identifier in the following order1. variable in current workspace2. built-in variable3. built-in m-file4. m-file in current directory5. m-file on search pathNote: m-files can be located in current directory, or in path

12Flow control - repetitionRepeats a code segment a fixed number of timesfor index=<vector><statements>endThe <statements> are executed repeatedly. At each iteration, the variable index is assigned a new value from <vector>.for k=1:12 kfac=prod(1:k); disp([num2str(k),’ ‘,num2str(kfac)]) end

16Flow control – conditional repetitionwhile-loopswhile <logical expression><statements>end<statements> are executed repeatedly as long as the <logical expression> evaluates to truek=1;while prod(1:k)~=Inf,k=k+1;enddisp([‘Largest factorial in Matlab:’,num2str(k)]);

17Flow control – conditional repetitionSolutions to nonlinear equationscan be found using Newton’s methodTask: write a function that finds a solution toGiven , iterate maxit times or until

19Function functions myfun.mDo we need to re-write newton.m for every new function?No! General purpose functions take other m-files as input.>> help feval>> [f,f_prime]=feval(’myfun’,0);myfun.mfunction [f,f_prime] = myfun(x)% MYFUN– Evaluate f(x) = exp(x)-sin(x)% and its first derivative% [f,f_prime] = myfun(x)f=exp(-x)-sin(x);f_prime=-exp(-x)-cos(x);