%% Matlab as a graphing scientific calculator (Part II) %% Introduction % % In this lab, you will learn how to create variables in Matlab and how to % create "anonymous functions". % %% Creating variables in Matlab % % So far, we have only entered expressions at the command line, and % obtained numerical results. However the real power of any programming % language comes from its ability to compute values, store them in % named variables, and use these stored values in later computations. % On a graphing calculator, you might have used "memory" buttons % for this. %

% Before we start, we are going to clear all global memory to make sure % we are starting with a clean workspace. We discuss the clear keyword below. % clear all %% % % We will also set the formatting to the "short, scientific notation" style % Recall that this style prints four digits after the decimal place, rather than the % 16, used in the "long" format. % format short e %% % % In Matlab, we store values using an assignment operator % = in the following manner : % x = 5 %% y = 7 %% % % The values x and y % are now stored in % Matlab's "global memory", and as long as they are in memory, they % can be recalled for later use and can participate in any of the % arithmetic operations that we have so far described or used % as arguments to functions. For example, we could now make the % assignment % z = x + y %% % % Variable names can be created using the following rules: %
%
% Rules for naming variables %
%
%
1. You may use upper and lower case letters, numbers and the 'underscore' % (_) character.
2. %
3. Variable names must not begin with % numbers or the underscore.
4. %
5. Matlab is case sensitive, so the variables % A and a are different variables. %
%
%

Here are some more examples of variable names. % x1 = 5 %% y2 = -25 %% pressure = 1000.013 %% Density = 1.01 %% x_velocity = -56.45 %% y_veloctiy = 12.0 %% Latitude = 180.1 %% latitude = -57.8 %% alpha_1 = sqrt(pi) %% beta_2 = 1/pi %% big_number = 1e56 %% small_number = 1e-100 %% Word of caution in choosing variable names % % Matlab will also allow you to % redefine reserved keywords. For example, we can set % pi = 3 %% % % If we were to now evaluate cos(pi), we would get % bad_value = cos(pi) %% % % instead of the expected value of -1. Worse yet, we can % redefine the cos function itself : % cos = 4.5 %% % %

If later in our program, we evaluate the cosine function, % we should expect an error.

%
% >> cos(pi)
% 
%
% Index exceeds matrix dimensions.
% 
% %% % % The precise meaning of this error may not yet be clear (basically, Matlab % thinks you are trying to find the third element of the array cos) but it should be obvious why redefining keywords % can lead to mysterious errors that can be hard to track down. % %% Clearing and listing variables from memory % % Suppose we want to restore the original meaning of % the Matlab keyword cos. We can do this by % "clearing" our definition from global memory. Let's also clear our % definition of pi as well % clear cos pi %% % % When we try our cos function again, we % get the expected result. % correct_value = cos(pi) %% % % Clearing the variables cos and pi % restored the original meaning of these keywords. We can also clear any % variables we previously defined. But before we do so, let's see what % we have currently stored in memory using the % who command % who %% % % A similar command whos shows you more % detail about each variable in your workspace: % whos %% % % This listing shows that each variable we have so far defined is a scalar (a '1x1' % array), it occupies 8 bytes, and it is of type double (Matlab uses the % term 'class' instead of the more familar 'type'). %

% We can now selectively clear variables from memory and then check % what is left in global memory % clear pressure Density x y z x1 y2 x_velocity y_velocity %% whos %% % % If we now try to check the value of one of the variables no longer in % memory, we get the following error : %
% >> Density
% 
%
% Undefined function or variable 'Density'.
% 
% %% % % To clear all the variables in memory, we use the command % clear all %% % % As you might expect, the whos has nothing to % show us once we have cleared all variables from memory. % whos %% Creating 'anonymous' functions in Matlab % % In many cases, you will want to evaluate expressions multiple times using % different values of the variables. While you might be able to cut and % paste the expressions into a script multiple times, this is error prone. % It is much better to create a "function" that can be called multiple % times using different arguments. %

% In Matlab, we can create functions in at least two different ways. The % first, and simplest, is to create what are called "anonymous functions". % These look very much like variables, but take an input argument. % %% % % Clear the global memory. % clear all; %% % % Define an 'anonymous function' using the special notation % f = @(x) 3*x + 2 %% % % The name of this function is called f, % and it takes a single argument x. We can now % call this function in a very natural way using parenthesis. For example, % f(3) %% f(-1.1) %% f(sqrt(7)) %% y = 5 %% f(2 - y) %% % % Here are some general guidelines to observe when creating function % handles. %
%
% Guidelines for creating function handles. %
%
%
1. Naming % anonymous functions follows the same rules as variable names.
2. %
3. Anonymous functions can take multiple arguments
4. %
5. Anonymous functions can depend on previously defined % variables.
6. %
7. Anonymous functions can depend on one another, and can % participate in all legal arithmetic expressions.
8. %
%
% %% % % Here are some examples showing how to apply the above rules. % g = @(x) 4*x^2/(2 + x) %% pressure = @(temp) 8.314*temp %% temp = 310 %% pressure(temp) %% % % Here is an example of a function which takes multiple arguments. % volume = @(h,w,d) h*w*d %% height = 2.3 %% width = 6.1 %% depth = 1.2 %% box_volume = volume(height,width,depth) %% % % Here is an example of a function which depends on a previously defined % variable. In this context, this variable might be called a % parameter, since it is not formally an argument to the function. % Note that the parameter must be defined before the function itself is % defined. %

% In the following, we create an equation of a line that relies on the % slope m and the y-intercept b. % m = 3.4 %% b = -4 %% my_line = @(x) m*x + b %% % % To call this function, we only pass in the single argument x. % my_line(5) %% % % A second way to include parameters in an anonymous function handle is to % treat them as additional arguments. For example, % my_line = @(x,m,b) m*x + b %% my_line(5,3.4,-4) %% % % This in many respects is preferable over the original method, since it is % clear exactly what values of m and b the function will use in its definition. %

% Finally, functions can depend on each other, and can be used in % expressions. For example, we can compose two functions to get a third % function. Suppose we have funtions % $f(x) = x^2$ and % $g(x) = x - 7$. % We could construct the function $h(x)$ by % composing $f$ and $g$ to get % $h = f \circ g$, or $h(x) = f(g(x))$. % f = @(x) x^2 %% g = @(x) x - 7 %% h = @(x) f(g(x)) %% % % And now $h(x)$ can be called like an % ordinary function % h(10) %% % % Anonymous functions can also be used in expressions in the same way as % variables or numerical values. % x = -1 %% y = f(x)^2/(sqrt(g(x)) + pi) %% % % Note that anonymous functions, like variables, appear in global memory % when we type whos. % whos %% % % To get more information on function handles, you can consult the Matlab % help system. Here is an excerpt from the command line help on the % keyword function_handle. %

%
% >> help function_handle
% ............
%      FUNHANDLE = @(ARGLIST)EXPRESSION constructs an anonymous function and
%      returns a handle to that function. The body of the function, to the
%      right of the parentheses, is a single MATLAB expression. ARGLIST is a
%      comma-separated list of input arguments. Execute the function by
%      calling it by means of the returned function handle, FUNHANDLE. For
%      the MATLAB Programming documentation.
%
%      To call the function referred to by a function handle value, use ordinary
%      parenthesis notation.  That is, specify the function handle variable
%      followed by a comma-separated list of input arguments enclosed in
%      parentheses. For example, HANDLE(ARG1, ARG2, ...). To call a
%      function_handle with no arguments, use empty parenthesis, e.g.,
%      HANDLE().
% ............
% 
% %% Lab exercises % %
% Use anonymous functions to evaluate the following mathematical expressions. %

%
%
1. $f(x) = \tanh(x/10)$. % Evaluate at % $x = 2\pi$ and % $x = -e$ %
2. %
%
3. % $h(x) = \frac{3x^3 - 1}{x^2 + 3}$. % Evaluate at % $x = \sqrt{3}i$ and % $x = \sqrt{1/3}$ %
4. %
5. $q(t) = \frac{s(t)}{s(t)^2 + 1}$, % where $s(t) = \cos(t)$. % Evaluate at % $t = \pi$ %
6. %
7. % $T(x,y) = 5x^{-2} - 1 + y + % \frac{x^2}{2y}$. % Evaluate at % $x = e^{\pi}, y = \sqrt{5}$ %
8. Suppose that $f(x) = \cos(x)$ and % $g(x) = x^2$. Write function handles for % the derivatives of both $f(x)$ and % $g(x)$ and use these functions to compute % the derivative of a function $h(x) = % f(x)g(x)$. What is $h'(-4.561)$?
9. %
10. Write a function that computes the distance between two points % $(x_1,y_1)$ and % $(x_2,y_2)$. Compute the distance % between successive minimum and maximums of the function % $f(x) = \cos(x)$. %
11. Write a function to compute the volume of a sphere of radius % $R$. Use your function to compute the volumes of the % Earth, Jupiter and Mars.
12. %
13. Use the ideal gas law $P=\rho % RT$ to compute the density $\rho \; % (kg/m^3)$, given the % temperature $T \; (K^\circ)$ % and pressure $P \; (Pa)$ of a gas. Use the % specific gas constant for dry air. % $R \approx 287.058 \;(J/(K^\circ\cdot % mol)$. What is the density of air at sea level, at 0, 10, 20 and 30 % degrees Celsius? Compare your answers with what you can find on the web. %
%
% %% % % Compare your results with the solutions. %