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

1) The anonymous function allows us to easily create mathematical functions, and

ID: 3815570 • Letter: 1

Question

1) The anonymous function allows us to easily create mathematical functions, and store them in variables. The documentation below provides additional details. http://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html:

For example, let’s say we wanted to implement the equation x^2 +2*x +1. We could use an anonymous function to create a new function and store in in f:

f = @(x) x^2 + 2*x + 1;

Now, we can say f(3), and it will evaluate the function at 3 (plugging in 3 for all x).

a) Write the MATLAB code to create the function x^2 + 1, and evaluate that function at x = 5.

b) Write the MATLAB code to loop from 1 to 5, and evaluate the function from part a at each iteration (the first iteration will be f(1), second f(2), etc.). You can use the looping variable as an argument to be passed to f.

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.

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

Answer for 1:

a)

f=@(x) (x^2 +1); % Defining th anonymous function.
% This is same as f(x)=x^2+1.
f(5) % Calling the function with argument 5

Output:
------------

ans = 26

b)

f=@(x) (x^2 +1); % Defining th anonymous function  
for i = [1:5] % using for loop starting with 1 till 5
f(i) % calling the function f with argument i
end

Output:
------------
ans = 2   
ans = 5   
ans = 10
ans = 17
ans = 26

Answer for question # 2:

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

Output:
-----------
ans = 2   
ans = 10
ans = 26
ans = 50
ans = 82

Please thumbs up if this answer helps you.