Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

(2) Often times, loops are not as simple as the following code: for i = [1:5] Co

ID: 3817160 • Letter: #

Question

(2) Often times, loops are not as simple as the following code:

for i = [1:5]

Consider the following example, we have three variables: a lower bound (a), an upper bound (b), and a step size (dx). If we wanted to loop from ‘a’ to ‘b’ by step size ‘dx’, we would write the following:

       for i = a:dx:b;

Using the same variables, answer the following questions.

a) Write the MATLAB code to loop from a, by step size dx, to one step before b (also known as b - dx). Use the variable i as your looping variable, as was done in the above examples.

       f=@(x) (x^2 +1); % Defining th anonymous function
       for i= 1:2:10 % using step size dx as 2 here. a(lower limit) is 2 and b (upper linit is 10)
       % values of i would be 1,3,5,7,9 and dx is median (mid point of each iteration)
       f(i)
       end

Write the MATLAB code to loop through all of the midpoints. Things to consider include:

The step size is still dx. In other words, the distance between each midpoint is dx.

The first midpoint is located between a and (a + dx).

The final midpoint is located between b and (b – dx).

Explanation / Answer

f=@(x) (x^2 +1); % Defining th anonymous function
    a=input('enter a');
    b=input('enter b');
   dx=input('enter dx');

     m=(2*a+dx)/2; %%First midpoint
     n=(2*b-dx)/2; %%Last Midpoint

for i= m:dx:n
    %Logic loop through all of the midpoints
    disp(i)
    end