Script M-file

Properties of Function M-Files

A MATLAB file of a special format that contains code with optional inputs and outputs is called function M-file.

Some advantages:

  • Functions can be called from inside of other script and function M-files.
  • Inputs allow variable values to be modified when calling the function (eg from the Command Window).
  • Outputs can be assigned to other variables at the Command Window or within a separate M-file.

Disadvantages:

  • A slight disadvantage with a function M-file is that you must follow the prescribed format, or else it won’t run correctly. Once you get the hang of that, you will see they are often very useful.

Exercise

> The following function M-file finds the value of the function f(x) = sin x + x3 for any value of x. Type it in and save as exercise1func.m in your Current Directory

% <insert your name and the date here>

% exercise1func.m

% input: x

% output: p, solved in terms of x

function p = exercise1func(x) %Note special format!

p = sin(x) + x^3

> Call this M-file from the Command Window using the following command and then update it to find the value of for p(x) for x=3, 4, 5, 6.

exercise1func(3) % returns value for x = 3

> Consider the case, when the variable x is an array [3 4 5 6]. Modify your function M-file so, that it will be able to work with arrays.