[go: up one dir, main page]

0% found this document useful (0 votes)
16 views28 pages

4 M-Files

The document explains the use of scripts and functions in MATLAB, highlighting their differences and purposes. Scripts are collections of commands executed sequentially, while functions accept inputs and return outputs with their own internal workspace. It also covers output commands like disp and fprintf, as well as importing and exporting data to and from Excel using xlsread and xlswrite commands.

Uploaded by

Sungaleli Yuen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views28 pages

4 M-Files

The document explains the use of scripts and functions in MATLAB, highlighting their differences and purposes. Scripts are collections of commands executed sequentially, while functions accept inputs and return outputs with their own internal workspace. It also covers output commands like disp and fprintf, as well as importing and exporting data to and from Excel using xlsread and xlswrite commands.

Uploaded by

Sungaleli Yuen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

M - FILES

Scripts and user-define functions


- Scripts or m-files are text files containing MATLAB code

- Use the MATLAB Editor or another text editor to create a


file containing the same statements you would type at the
MATLAB command line

- Save the file under a name that ends with “.m”

- We can either create a Script or a Function. The difference


between a script and a function will be explained below

- Both will be saved as m- files, but the usage will be slightly


different
Scripts Vs. Function Files
 Scripts
- A collection of commands that you would execute in the
Command Window
- Used for automating repetitive tasks
 Functions (user-defined functions)
- Operate on information (inputs) fed into them and return
outputs
- Have a separate workspace and internal variables that is only
valid inside the function
- Your own user-defined functions work the same way as the
built-in functions you use all the time, such as plot(), rand(),
mean(), std(), etc.
Script
 A Script is a collection of MATLAB commands and functions
that is bundled together in a m-file (are external file that contains
a sequence of MATLAB statements). When you run the Script, all
the commands are executed sequentially

 In the Editor you create a sequence of MATLAB commands that


you save as a m-file(the file extension ends with .m). Push the
“Run” button when you want to run your program
 Script side-effect is that variables already existing in the
workspace may be overwritten also the execution can be affected
by the state variables in the workspace
Notes About Script Files
 A script file is a sequence of MATLA commands, also called a
program

 When a script file runs (is executed), MATLAB executes the


commands in the order they are written, just as if they were typed
in the Command Window

 When a script file has a command that generates an output (e.g.,


assignment of a value to a variable without a semicolon at the
end), the output is displayed in the Command Window
Cont.. .

 Using a script file is convenient because it can be edited


(corrected or otherwise changed) and executed many times

 Script files can be typed and edited in any text editor and then
pasted into the MATLAB editor

 Script files are also called M-files because the extension .m is


used when they are saved
OUTPUT COMMANDS
 Two commands that are frequently used to generate output are
disp and fprintf

The disp Command


The disp command is used to display the elements of a variable
without displaying the name of the variable, and to display text

disp(name of a variable) or disp(‘text as string’)

Keep in mind !!!


Every time the disp command is executed, the display it generates
appears in a new line
Cont.. .
The fprintf Command

 The fprintf command can be used to display output (text and


data) on the screen or to save it to a file

 With this command (unlike with the disp command) the


output can be formatted

 With many available options, the fprintf command can be


long and complicated

 To avoid confusion, the command is presented gradually


Using the fprintf command to display text

fprintf(‘text typed in as a string’)

Example
Cont.. .
 With the fprintf command it is possible to start a new line in the
middle of the string.
 This is done by inserting \n before the character that will start the
new line

 When a program has more than one fprintf command, the


display generated is continuous (the fprintf command does not
automatically start a new line)
 To start a new line with the fprintf command, \n must be typed at
the start of the string
Using the fprintf command to display a mix
of text and numerical data
Cont.. .
 The flag, which is optional, can be one of the following three
characters

Character Description
– (minus sign) : Left-justifies the number within the field
+ (plus sign) : Prints a sign character (+ or –) in front of the
number
0 (zero) : Adds zeros if the number is shorter than the
field
Here are some examples of flags in use:

- %-5.2f : Left-justifies the data

- %+5.2f : Always prints a sign character (+ or –)


for numeric values

- % 5.2f : Inserts a space before the value

- %05.2f : Pads to field width with zeros before


the value
Cont.. .
 The last element in the formatting elements, which is required, is
the conversion character, which specifies the notation in which
the number is displayed

Some of the common notations are:

e : Exponential notation using lowercase e


. . , 1.709098 001
E : Exponential notation using uppercase E
. . , 1.709098 001
f : Fixed-point notation . . , 17.090980
Cont... .

Note!!

With the fprintf command it is possible to insert more than one number
(value of a variable) within the text

fprintf (‘..text...%g...%g...%f...’,variable1,variable2,variable3)
Additional remarks !!!
 To place a single quotation mark in the displayed text, type two
single quotation marks in the string inside the command

 To display the % character in the text, type %%

 The fprintf command is vectorized. This means that when a


variable that is a vector or a matrix is included in the command,
the command repeats itself until all the elements are displayed. If
the variable is a matrix, the data is used column by column.
Some common format options
- %s - print a string.

- %c - print a single character.

- %d - print a whole number.

- %f - print a floating point number.

- \n - print a new line


- \t - print a tab.
- \\ - print a slash
- %% - print a percent sign.
THE save AND load COMMANDS
IMPORTING AND EXPORTING DATA
 MATLAB is often used for analyzing data that was recorded in
experiments or generated by other computer programs. This can
be done by first importing the data into MATLAB

 Similarly, data that is produced by MATLAB sometimes needs


to be transferred to other computer applications

 There are various types of data (numerical, text, audio,


graphics, and images)

 Importing data can be done either by using commands or by


using the Import Wizard
Importing and exporting data into and from Excel
 Importing data from Excel is done with the xlsread command.
When the command is executed, the data from the spreadsheet is
assigned as an array to a variable

variable_name = xlsread(‘filename’)

 ‘filename’ (typed as a string) is the name of the Excel file

 The directory of the Excel file must be either the current


directory or listed in the search path.
Cont.. .
 If the Excel file has more than one sheet, the data will be
imported from the first sheet

 When an Excel file has several sheets, the xlsread command can
be used to import data from a specified sheet

variable_name = xlsread(‘filename’,‘sheet_name’)
Cont.. .
o Another option is to import only a portion of the data that is in
the spreadsheet. This is done by typing an additional argument in
the command

variable_name = xlsread(‘filename’,‘sheet_name’,‘range’)

o The ‘range’ (typed as a string) is a rectangular region of the


spreadsheet defined by the addresses (in Excel notation) of the
cells at opposite corners of the region
o For example, ‘C2:E5’ is a region of rows 2, 3, 4, and 5 and
columns C, D, and E
Cont.. .
 Exporting data from MATLAB to an Excel spreadsheet is done
by using the xlswrite command

xlswrite(‘filename’,variable_name)

 ‘filename’ (typed as a string) is the name of the Excel file to


which the data is exported

 The file must be in the current directory. If the file does not
exist, a new Excel file with the specified name will be created
Cont.. .
 variable_name is the name of the variable in MATLAB
with the assigned data that is being exported

 The arguments ‘sheet_name’ and ‘range’ can be added to


the xlswrite command to export to a specified sheet and to a
specified range of cells, respectively
Using the Import Wizard

On your night group


discussions practice on
how to use
Functions

 MATLAB includes more than 1000 built-in functions that you


can use, but sometimes you need to create your own functions

 Functions are programs ( or routines) that accept input arguments


and return output arguments. Each M-file function ( or function)
has its own area of workspace, separated from the MATLAB
base workspace
Functions
 To define your own function in MATLAB, use the following
syntax:-
- function output = function_name(input)
% function with one input and one output
- function [out1,out2] = function_name(in1,in2,..)
% function with multiple inputs and multiple outputs
Example:
Difference between scripts and Functions
SCRIPTS FUNCTIONS
• Do not accept input argument • Can accept input arguments
or return output arguments and return output arguments
• Store variables in a workspace • Store variables in a workspace
that is shared with other scripts internal to the function
• Are useful for automating a • Are useful for extending the
series of commands MATLAB language for your
application

You might also like