41 PDFsam Matlab Prog
41 PDFsam Matlab Prog
helpFile = which('help');
[helpPath,name,ext] = fileparts(helpFile);
The current workspace now contains three variables from fileparts: helpPath, name, and ext. In
this case, the variables are small. However, some functions return results that use much more
memory. If you do not need those variables, they waste space on your system.
If you do not use the tilde operator, you can request only the first N outputs of a function (where N is
less than or equal to the number of possible outputs) and ignore any remaining outputs. For example,
request only the first output, ignoring the second and third.
helpPath = fileparts(helpFile);
If you request more than one output, enclose the variable names in square brackets, []. The
following code ignores the output argument ext.
[helpPath,name] = fileparts(helpFile);
To ignore function outputs in any position in the argument list, use the tilde operator. For example,
ignore the first output using a tilde.
[~,name,ext] = fileparts(helpFile);
You can ignore any number of function outputs using the tilde operator. Separate consecutive tildes
with a comma. For example, this code ignores the first two output arguments.
[~,~,ext] = fileparts(helpFile);
See Also
More About
• “Ignore Inputs in Function Definitions” on page 21-10
1-3
1 Syntax Basics
Variable Names
In this section...
“Valid Names” on page 1-4
“Conflicts with Function Names” on page 1-4
Valid Names
A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB is case
sensitive, so A and a are not the same variable. The maximum length of a variable name is the value
that the namelengthmax command returns.
You cannot define variables with the same names as MATLAB keywords, such as if or end. For a
complete list, run the iskeyword command.
Check whether a proposed name is already in use with the exist or which function. exist returns
0 if there are no existing variables, functions, or other artifacts with the proposed name. For example:
exist checkname
ans =
0
If you inadvertently create a variable with a name conflict, remove the variable from memory with the
clear function.
Another potential source of name conflicts occurs when you define a function that calls load or eval
(or similar functions) to add variables to the workspace. In some cases, load or eval add variables
that have the same names as functions. Unless these variables are in the function workspace before
the call to load or eval, the MATLAB parser interprets the variable names as function names. For
more information, see:
See Also
clear | exist | iskeyword | isvarname | namelengthmax | which
1-4
Case and Space Sensitivity
In MATLAB code, use an exact match with regard to case for variables, files, and functions. For
example, if you have a variable, a, you cannot refer to that variable as A. It is a best practice to use
lowercase only when naming functions. This is especially useful when you use both Microsoft®
Windows® and UNIX®1 platforms because their file systems behave differently with regard to case.
When you use the help function, the help displays some function names in all uppercase, for
example, PLOT, solely to distinguish the function name from the rest of the text. Some functions for
interfacing to Oracle® Java® software do use mixed case and the command-line help and the
documentation accurately reflect that.
Spaces
Blank spaces around operators such as -, :, and ( ), are optional, but they can improve readability.
For example, MATLAB interprets the following statements the same way.
y = sin (3 * pi) / 2
y=sin(3*pi)/2
However, blank spaces act as delimiters in horizontal concatenation. When defining row vectors, you
can use spaces and commas interchangeably to separate elements:
A = [1, 0 2, 3 3]
A =
1 0 2 3 3
Because of this flexibility, check to ensure that MATLAB stores the correct values. For example, the
statement [1 sin (pi) 3] produces a much different result than [1 sin(pi) 3] does.
[1 sin (pi) 3]
[1 sin(pi) 3]
ans =
1. UNIX is a registered trademark of The Open Group in the United States and other countries.
1-5
1 Syntax Basics
For introductory information on calling functions, see “Calling Functions”. For information related to
defining functions, see “Create Functions in Files” on page 20-2.
In function syntax, inputs can be data, variables, and even MATLAB expressions. If an input is data,
such as the numeric value 2 or the string array ["a" "b" "c"], MATLAB passes it to the function
as-is. If an input is a variable MATLAB will pass the value assigned to it. If an input is an expression,
like 2+2 or sin(2*pi), MATLAB evaluates it first, and passes the result to the function. If the
functions has outputs , you can assign them to variables as shown in the example syntax above.
Command syntax is simpler but more limited. To use it, separate inputs with spaces rather than
commas, and do not enclose them in parentheses.
functionName input1 ... inputN
With command syntax, MATLAB passes all inputs as character vectors (that is, as if they were
enclosed in single quotation marks) and does not assign outputs to variables. To pass a data type
other than a character vector, use the function syntax. To pass a value that contains a space, you have
two options. One is to use function syntax. The other is to put single quotes around the value.
Otherwise, MATLAB treats the space as splitting your value into multiple inputs.
If a value is assigned to a variable, you must use function syntax to pass the value to the function.
Command syntax always passes inputs as character vectors and cannot pass variable values. For
example, create a variable and call the disp function with function syntax to pass the value of the
variable:
A = 123;
disp(A)
You cannot use command syntax to pass the value of A, because this call
disp A
is equivalent to
1-6
Choose Command Syntax or Function Syntax
disp('A')
and returns
filename = 'accounts.txt';
A = int8(1:8);
B = A;
or
Some functions expect character vectors for variable names, such as save, load, clear, and whos.
For example,
requests information about variable X in the example file durer.mat. This command is equivalent to
whos('-file','durer.mat','X')
ls ./d
This could be a call to the ls function with './d' as its argument. It also could represent element-
wise division on the array ls, using the variable d as the divisor.
1-7
1 Syntax Basics
If you issue this statement at the command line, MATLAB can access the current workspace and path
to determine whether ls and d are functions or variables. However, some components, such as the
Code Analyzer and the Editor/Debugger, operate without reference to the path or workspace. When
you are using those components, MATLAB uses syntactic rules to determine whether an expression is
a function call using command syntax.
In general, when MATLAB recognizes an identifier (which might name a function or a variable), it
analyzes the characters that follow the identifier to determine the type of expression, as follows:
ls =d
• An open parenthesis after an identifier implies a function call. For example:
ls('./d')
• Space after an identifier, but not after a potential operator, implies a function call using command
syntax. For example:
ls ./d
• Spaces on both sides of a potential operator, or no spaces on either side of the operator, imply an
operation on variables. For example, these statements are equivalent:
ls ./ d
ls./d
Therefore, MATLAB treats the potentially ambiguous statement ls ./d as a call to the ls function
using command syntax.
The best practice is to avoid defining variable names that conflict with common functions, to prevent
any ambiguity.
See Also
“Calling Functions” | “Create Functions in Files” on page 20-2
1-8
Resolve Error: Undefined Function or Variable
Issue
You may encounter the following error message, or something similar, while working with functions
or variables in MATLAB:
These errors usually indicate that MATLAB cannot find a particular variable or MATLAB program file
in the current directory or on the search path.
Possible Solutions
Verify Spelling of Function or Variable Name
One of the most common causes is misspelling the function or variable name. Especially with longer
names or names containing similar characters (such as the letter l and numeral one), it is easy to
make mistakes and hard to detect them.
Often, when you misspell a MATLAB function, a suggested function name appears in the Command
Window. For example, this command fails because it includes an uppercase letter in the function
name:
accumArray
When this happens, press Enter to execute the suggested command or Esc to dismiss it.
Object methods are typically called using function syntax: for instance method(object,inputs).
Alternatively, they can be called using dot notation: for instance object.method(inputs). One
common error is to mix these syntaxes. For instance, you might call the method using function syntax,
but to provide inputs following dot notation syntax and leave out the object as an input: for instance,
method(inputs). To avoid this, when calling an object method, make sure you specify the object
first, either through the first input of function syntax or through the first identifier of dot notation.
When you write a function, you establish its name when you write its function definition line. This
name should always match the name of the file you save it to. For example, if you create a function
named curveplot,
then you should name the file containing that function curveplot.m. If you create a pcode file for
the function, then name that file curveplot.p. In the case of conflicting function and file names, the
file name overrides the name given to the function. In this example, if you save the curveplot
1-9
1 Syntax Basics
function to a file named curveplotfunction.m, then attempts to invoke the function using the
function name will fail:
curveplot
Undefined function or variable 'curveplot'.
If you encounter this problem, change either the function name or file name so that they are the
same.
To Locate the file that defines this function, use the MATLAB Find Files utility as follows:
1
On the Home tab, in the File section, click Find Files.
2 Under Find files named, enter *.m
3 Under Find files containing text, enter the function name.
4 Click the Find button
If you are unable to use a built-in function from MATLAB or its toolboxes, make sure that the function
is installed and is the correct version.
If you do not know which toolbox contains the function you need, search for the function
documentation at https://www.mathworks.com/help. The toolbox name appears at the top of the
function reference page. Alternatively, for steps to identify toolboxes that a function depends on, see
“Identify Program Dependencies” on page 25-2.
Once you know which toolbox the function belongs to, use the ver function to see which toolboxes
are installed on the system from which you run MATLAB. The ver function displays a list of all
currently installed MathWorks® products. If you can locate the toolbox you need in the output
displayed by ver, then the toolbox is installed. If you cannot, you need to install it in order to use it. If
1-10
Resolve Error: Undefined Function or Variable
you cannot, you need to install it in order to use it. For help with installing MathWorks products, see
“Installation and Licensing”.
Tip If you have a custom file path, this step will delete it.
The MATLAB search path is a subset of all the folders in the file system. MATLAB uses the search
path to locate files used with MathWorks products efficiently. For more information, see “What Is the
MATLAB Search Path?”.
If the function you are attempting to use is part of a toolbox, then verify that the toolbox is available
using ver.
Because MATLAB stores the toolbox information in a cache file, you need to first update this cache
and then reset the path.
1
On the Home tab, in the Environment section, click Preferences.
A small dialog box opens warning that you will lose your current path settings if you proceed.
Select Yes if you decide to proceed.
Run ver to see if the toolbox is installed. If not, you may need to reinstall this toolbox to use this
function. For more information about installing a toolbox, see How do I install additional toolboxes
into an existing installation of MATLAB.
Once ver shows your toolbox, run the following command to see if you can find the function:
replacing <functionname> with the name of the function. If MATLAB finds your function file, it
presents you with the path to it. You can add that file to the path using the addpath function. If it
does not, make sure the necessary toolbox is installed, and that it is the correct version.
If you are unable to use a built-in function from a MATLAB toolbox and have confirmed that the
toolbox is installed, make sure that you have an active license for that toolbox. Use license to
display currently active licenses. For additional support for managing licenses, see “Manage Your
Licenses”.
1-11
2
Program Components
Arithmetic Operators
Symbol Role More Information
+ Addition plus
+ Unary plus uplus
- Subtraction minus
- Unary minus uminus
.* Element-wise multiplication times
* Matrix multiplication mtimes
./ Element-wise right division rdivide
/ Matrix right division mrdivide
.\ Element-wise left division ldivide
\ Matrix left division mldivide
Relational Operators
Symbol Role More Information
== Equal to eq
~= Not equal to ne
> Greater than gt
>= Greater than or equal to ge
< Less than lt
<= Less than or equal to le
Logical Operators
Symbol Role More Information
& Find logical AND and
| Find logical OR or
&& Find logical AND (with short- Logical Operators: Short-
circuiting) Circuit && ||
2-2
MATLAB Operators and Special Characters
Special Characters
@ Name: At symbol
Uses:
Description: The @ symbol forms a handle to either the named function that follows the @
sign, or to the anonymous function that follows the @ sign. You can also use @ to call
superclass methods from subclasses.
Examples
fhandle = @myfun
disp@MySuper(obj)
Call the superclass constructor from a subclass using the object being constructed:
obj = obj@MySuper(arg1,arg2,...)
More Information:
2-3
2 Program Components
Uses:
• Decimal point
• Element-wise operations
• Structure field access
• Object property or method specifier
Description: The period character separates the integral and fractional parts of a
number, such as 3.1415. MATLAB operators that contain a period always work element-
wise. The period character also enables you to access the fields in a structure, as well as
the properties and methods of an object.
Examples
Decimal point:
102.5543
Element-wise operations:
A.*B
A.^2
myStruct.f1
myObj.PropertyName
More Information
2-4
MATLAB Operators and Special Characters
Description: Three or more periods at the end of a line continues the current command
on the next line. If three or more periods occur before the end of a line, then MATLAB
ignores the rest of the line and continues to the next line. This effectively makes a
comment out of anything on the current line that follows the three periods.
Examples
Break a character vector up on multiple lines and concatenate the lines together:
To comment out one line in a multiline command, use ... at the beginning of the line to
ensure that the command remains complete. If you use % to comment out a line it
produces an error:
y = 1 +...
2 +...
% 3 +...
4;
However, this code runs properly since the third line does not produce a gap in the
command:
y = 1 +...
2 +...
... 3 +...
4;
More Information
2-5
2 Program Components
, Name: Comma
Uses: Separator
Examples
A = [12,13; 14,15]
Separate subscripts:
A(1,2)
[Y,I] = max(A,[],2)
More Information
• horzcat
2-6
MATLAB Operators and Special Characters
: Name: Colon
Uses:
• Vector creation
• Indexing
• For-loop iteration
Description: Use the colon operator to create regularly spaced vectors, index into
arrays, and define the bounds of a for loop.
Examples
Create a vector:
x = 1:10
x = 1:3:19
A(:)
A = rand(3,4);
A(:) = 1:12;
A(2:5,3)
A(:,3)
x = 1;
for k = 1:25
x = x + x^2;
end
More Information
• colon
• “Creating, Concatenating, and Expanding Matrices”
2-7
2 Program Components
; Name: Semicolon
Uses:
Examples
A = [12,13; 14,15]
Y = max(A);
More Information
• vertcat
2-8
MATLAB Operators and Special Characters
( ) Name: Parentheses
Uses:
• Operator precedence
• Function argument enclosure
• Indexing
Examples
Precedence of operations:
(A.*(B./C)) - D
plot(X,Y,'r*')
C = union(A,B)
Indexing:
A(3,:)
A(1,2)
A(1:5,1)
More Information
2-9
2 Program Components
Uses:
• Array construction
• Array concatenation
• Empty matrix and array element deletion
• Multiple output argument assignment
Examples
X = [10 12 -3]
A = rand(3);
A = [A; 10 20 30]
A = []
A(:,1) = []
[C,iA,iB] = union(A,B)
More Information
2-10