Docsity

Understanding Matlab Functions: Definition, Use, and Creation, Study notes of Computer Science

Toggle sidebar
bg1
2-2
What is a Matlab function?
How does the plot function work?
What Matlab functions are available to do Data
Analysis?
How can you create your own function ?
Readings: Matlab by Pratap Chapter 4.2, 4.3
Chapter 5.3
Chapter 6.1
2-3
Basic Mathematical Functions (see p62-64 in textbook) However , since
there are hundred s of Matlab functions, a useful tool is M atlab Helpdesk.
Exponential Function
>> exp(0) (exponential function ex)
ans = 1
name argument parenthesis
>> x = [-1 0 1];
>> exp(x)
ans = 0.3679 1.0000 2.7183 ( [exp (-1), exp(0), exp(1)] )
The exp function argum ent can be a scalar, vector or matri x.
4
Three forms of the use of a function in Matlab are:
>> VAR = function_name(arg1,arg2, …);
>> [VAR1,VAR2,...] = function_name(arg1,arg2, …);
>> function_name(arg1,arg2, …);
A Matlab function like a mathematical function is a rule
where given a certain input or inputs, the rule tells you how
to compute the output value or how to produce an effect
(e.g. the plot function produces a figure).
The inputs are called the “arguments” to the function.
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Understanding Matlab Functions: Definition, Use, and Creation and more Study notes Computer Science in PDF only on Docsity!

2-

What is a Matlab function?

How does the plot function work?

What Matlab functions are available to do Data

Analysis?

How can you create your own function?

Readings: Matlab by Pratap Chapter 4.2, 4.

Chapter 5.

Chapter 6.

2-

Basic Mathematical Functions (see p62-64 in textbook) However, since there are hundreds of Matlab functions, a useful tool is Matlab Helpdesk.

Exponential Function

>> exp(0) (exponential function ex^ )

ans = 1

name argument parenthesis

>> x = [-1 0 1];

>> exp(x)

ans = 0.3679 1.0000 2.7183 ( [exp(-1), exp(0), exp(1)] )

The exp function argument can be a scalar, vector or matrix.

4

Three forms of the use of a function in Matlab are:

>> VAR = function_name(arg1,arg2, …);

>> [VAR1,VAR2,...] = function_name(arg1,arg2, …);

>> function_name(arg1,arg2, …);

A Matlab function like a mathematical function is a rule where given a certain input or inputs, the rule tells you how to compute the output value or how to produce an effect (e.g. the plot function produces a figure).

The inputs are called the “arguments” to the function.

As an illustration, a function can be likened to the sequence of instructions on an income tax form(see next two slides).

  • The instructions must be followed in sequential order.
  • Fields (or boxes in the form represent variables). All variables in a function are local to that function. They cannot been seen by other users filling out other forms.
  • Fields in the form that must be filled in with information provided by the person whose tax is being computed are called parameters. The values entered in these fields, (like name , social security number),... are called input arguments.
  • If the taxpayer recieves a return this amount is always found in one specific field on the form, field 67a. This field is called an output variable.

name field

refund amount

amount due

2-

Example: Plot the sine function using the built-in function “sin”. (see section 6.1)

>> x = -10 : .1 : 10; % (remember ; suppresses output)

>> y = sin(x); % x in radians

>> plot(x,y);

By default Matlab will connect the points (xi ,yi ) with a straight line. A more general version of the plot command is:

plot(x,y,’color_linestyle_marker’);

where color is:

cyan magenta yellow red green blue white black c m y r g b w k

2-

vec1 = [-2 ; 3 ; 4] ; vec2 = [-2 3 4] ; sum(vec1) input is a 3 x 1 column vector and output is a scalar.

ans = 5

sum(vec2) input is a 1 x 3 row vector and output is a scalar. ans = 5

Matlab’s built-in functions accept a wide variety of array sizes. Example: The built-in function sum.

(see section 5.3 for examples) 2-

Users can add to Matlab’s built-in functions by “programming” a function. A program in Matlab is either in the form of a script or a function. Programming a function is described in the Matlab book in Chapter 4.2 and scripts are described in Chapter 4.1.

2-

Programming -

  • A process for obtaining a computer solution to a problem.
  • A computer program is a sequence of instructions that tell the computer what to do.

2-

  • Modular Programming Break complicated tasks up into pieces(functions).
  • Functions can “call” other functions. This means you don’t have to re-write the code for the function again and again.
  • Variables in Functions are “local”. All variables in the function are “ local ” by default. That means that if you have a variable in your workspace with the same name as the variable in a function, then assigning a value to the variable in the function has no affect on the variable in the workspace. That is, a function cannot accidentally change (destroy) the data in your workspace.

2-

  1. Problem Definition
  2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.)
  3. Develop Algorithm (processing steps to solve problem)
  4. Write the "Program" (Code) (instruction sequence to be carried out by the computer)
  5. Test and Debug the Code
  6. Run Code

Note: These steps correspond to those found in the course C book p. 37.

2-

  1. Problem Definition Write a function that converts a temperature in Fahrenheit to Celsius.
  2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Use the fact that celsius = (fahr - 32) * 5/

2-

Natural-Language Algorithm

The function “definition” should list one input variable named fahr and one output variable celsius. Compute the value of the celsius temperature and assign the value to a variable “celsius” The “function” mechanism of Matlab will automatically return the value in the variable celsius when the function is used (called) at the Matlab prompt.

  1. Develop Algorithm (processing steps to solve problem)

2-

  1. Write the “Function" (Code) (instruction sequence to be carried out by the computer)

Any sequence of Matlab commands can be put in a file. The file suffix should end with a “.m”. The sequence of commands will be executed (from the top of the file down, command by command).

edit to open the Matlab editor and create a new file. Then type (and save) the following: function celsius = F_to_C(fahr) % This function converts Fahrenheit to Celsius. celsius = (fahr -32)*5/9;

Click “File” and then “Save As” to name the file “F_to_C.m”.

2-

Improved documentation for the F_to_C function.

function celsius = F_to_C(fahr) % function celsius = F_to_C(fahr) % This function converts Fahrenheit to Celsius. % input fahr can be a scalar or vector of temps in degree F % output celsius is a scalar or vector of temps in degree C % Programmer: Tom Gambill % Date: 1/30/ celsius = (fahr -32)*5/9;

2-

  1. Problem Definition Write a function that computes the time for a falling object to hit the ground.
  2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.)

Use the fact that height_t = height_0 + velocity_0 time + 1/2 * g * time time, where height_t is the height of the object at any given time (in seconds), g is the acceleration due to gravity, -9.8 m/s^2. velocity_0 is the velocity at time = 0. Therefore to compute the time to impact, set height_t = 0 and solve for time. This equation (after doing some algebra)can be written as:**

0 = height_0 + velocity_0 * time + 1/2 * g * time * time

This is a quadratic formula in terms of the variable time.

2-

Natural-Language Algorithm

Initial values of height_0 and velocity_0 are provided via the arguments when the function is called.

Solve quadratic formula for time

Quadratic formula has two solutions, select the positive value as the result to be returned.

  1. Develop Algorithm (processing steps to solve problem)
  2. (continued)

The input arguments to the function consists of scalar values for height_ and velocity_0 and the output is the exact time (in seconds) of contact with the ground. Assumptions: No air resistance and time = 0 when object begins decent. (Also height_0 > 0 implicit)

2-

  1. Write the “Function" (Code) (instruction sequence to be carried out by the computer) Use the Matlab editor to create a file “time_to_impact.m”. function time = time_to_impact(height_0,velocity_0) % function time = time_to_impact(height_0,velocity_0) % Input: Two scalars height_0 (meters) and velocity_0 (meters/sec) % Output: time to impact (sec) given initial height is % height_0 and initial velocity is velocity_0. % Programmer: Tom Gambill % Date: 9/10// % Assumptions: No air resistance % time = zero when object begins decent % g = 9.8 is constant p = [-.5*9.8 , velocity_0, height_0]; time=roots(p); time = max(time);

2-

  1. Test and Debug the Code Although the value of the function is assigned to the variable time, when you execute the function you can assign the value of the function to any variable.(see next slide)
  2. Run Code Note: The prefix of the Unix filename must be the same as the name of the function. e.g. if the function name is “time_to_impact” then the filename in Unix must be “time_to_impact.m”. Also, don’t use the same name for a function and a variable in your workspace.

(see the next slide for ways to “run” or execute the function)

2-

Body of the function

Note: One statement in the body of the function should be of the form, output_variable = expression;

function output_variable = function_name( input_variables )

% The line above is called the function definition line.

% Simple functions have only one output variable..

% A line that begins with a “%” symbol is called a comment.

% Comments are ignored by Matlab but necessary for humans.

2-

time_to_impact uses the built-in functions, roots , and max.

The function roots (see p. 153) computes all the roots of a

polynomial. In Matlab polynomials are represented by vectors. e.g. the polynomial, x 2 - 1 is represented by

>> p = [1 0 -1]; % p is just a vector

To compute all the roots (x-values where p(x) = 0) of this polynomial type,

>> roots(p)

ans =