0% found this document useful (0 votes)
10 views

41 PDFsam Matlab Prog

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

41 PDFsam Matlab Prog

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Ignore Function Outputs

Ignore Function Outputs


This example shows how to ignore specific outputs from a function using the tilde (~) operator.

Request all three possible outputs from the fileparts function.

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.

Examples of valid names: Examples of invalid names:


x6 6x
lastValue end
n_factorial n!

Conflicts with Function Names


Avoid creating variables with the same name as a function (such as i, j, mode, char, size, and
path). In general, variable names take precedence over function names. If you create a variable that
uses the name of a function, you sometimes get unexpected results.

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:

• “Unexpected Results When Loading Variables Within a Function”


• “Alternatives to the eval Function” on page 2-86

See Also
clear | exist | iskeyword | isvarname | namelengthmax | which

1-4
Case and Space Sensitivity

Case and Space Sensitivity


MATLAB code is sensitive to casing, and insensitive to blank spaces except when defining arrays.

Uppercase and Lowercase

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]

Error using sin


Not enough input arguments.

[1 sin(pi) 3]

ans =

1.0000 0.0000 3.0000

1. UNIX is a registered trademark of The Open Group in the United States and other countries.

1-5
1 Syntax Basics

Choose Command Syntax or Function Syntax


MATLAB has two ways of calling functions, called function syntax and command syntax. This page
discusses the differences between these syntax formats and how to avoid common mistakes
associated with command syntax.

For introductory information on calling functions, see “Calling Functions”. For information related to
defining functions, see “Create Functions in Files” on page 20-2.

Command Syntax and Function Syntax


In MATLAB, these statements are equivalent:
load durer.mat % Command syntax
load('durer.mat') % Function syntax

This equivalence is sometimes referred to as command-function duality.

All functions support this standard function syntax:


[output1, ..., outputM] = functionName(input1, ..., inputN)

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)

This code returns the expected result,


123

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

Avoid Common Syntax Mistakes


Suppose that your workspace contains these variables:

filename = 'accounts.txt';
A = int8(1:8);
B = A;

The following table illustrates common misapplications of command syntax.

This Command... Is Equivalent to... Correct Syntax for Passing Value


open filename open('filename') open(filename)
isequal A B isequal('A','B') isequal(A,B)
strcmp class(A) int8 strcmp('class(A)','int8') strcmp(class(A),'int8')
cd tempdir cd('tempdir') cd(tempdir)
isnumeric 500 isnumeric('500') isnumeric(500)
round 3.499 round('3.499'), which is round(3.499)
equivalent to round([51 46 52
57 57])
disp hello world disp('hello','world') disp('hello world')

or

disp 'hello world'


disp "string" disp('"string"') disp("string")

Passing Variable Names

Some functions expect character vectors for variable names, such as save, load, clear, and whos.
For example,

whos -file durer.mat X

requests information about variable X in the example file durer.mat. This command is equivalent to

whos('-file','durer.mat','X')

How MATLAB Recognizes Command Syntax


Consider the potentially ambiguous statement

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:

• An equal sign (=) implies assignment. For example:

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

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:

Undefined function or variable 'x'.

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

Undefined function or variable 'accumArray'.

Did you mean:


>> accumarray

When this happens, press Enter to execute the suggested command or Esc to dismiss it.

Verify Inputs Correspond to the Function Syntax

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.

Make Sure Function Name Matches File Name

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,

function curveplot(xVal, yVal)


- program code -

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

Make Sure Necessary Toolbox Is Installed and Correct Version

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”.

Verify Path Used to Access Function Toolbox

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.

The Preference dialog box appears.


2 On the MATLAB > General page, select Update Toolbox Path Cache.
3
On the Home tab, in the Environment section, select Set Path.

The Set Path dialog box opens.


4 Select Default.

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:

which -all <functionname>

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.

Confirm The License Is Active

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

• “MATLAB Operators and Special Characters” on page 2-2


• “Array vs. Matrix Operations” on page 2-20
• “Compatible Array Sizes for Basic Operations” on page 2-25
• “Array Comparison with Relational Operators” on page 2-29
• “Operator Precedence” on page 2-32
• “Average Similar Data Points Using a Tolerance” on page 2-34
• “Group Scattered Data Using a Tolerance” on page 2-36
• “Bit-Wise Operations” on page 2-38
• “Perform Cyclic Redundancy Check” on page 2-44
• “Conditional Statements” on page 2-47
• “Loop Control Statements” on page 2-49
• “Regular Expressions” on page 2-51
• “Lookahead Assertions in Regular Expressions” on page 2-63
• “Tokens in Regular Expressions” on page 2-66
• “Dynamic Regular Expressions” on page 2-72
• “Comma-Separated Lists” on page 2-79
• “Alternatives to the eval Function” on page 2-86
2 Program Components

MATLAB Operators and Special Characters


This page contains a comprehensive listing of all MATLAB operators, symbols, and special characters.

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

(also known as backslash)


.^ Element-wise power power
^ Matrix power mpower
.' Transpose transpose
' Complex conjugate transpose ctranspose

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

Symbol Role More Information


|| Find logical OR (with short-
circuiting)
~ Find logical NOT not

Special Characters
@ Name: At symbol

Uses:

• Function handle construction and reference


• Calling superclass methods

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

Create a function handle to a named function:

fhandle = @myfun

Create a function handle to an anonymous function:

fhandle = @(x,y) x.^2 + y.^2;

Call the disp method of MySuper from a subclass:

disp@MySuper(obj)

Call the superclass constructor from a subclass using the object being constructed:

obj = obj@MySuper(arg1,arg2,...)

More Information:

• “Create Function Handle” on page 13-2


• “Call Superclass Methods on Subclass Objects”

2-3
2 Program Components

. Name: Period or dot

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

Structure field access:

myStruct.f1

Object property specifier:

myObj.PropertyName

More Information

• “Array vs. Matrix Operations” on page 2-20


• “Structures”
• “Access Property Values”

2-4
MATLAB Operators and Special Characters

... Name: Dot dot dot or ellipsis

Uses: Line continuation

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.

Note MATLAB interprets the ellipsis as a space character. Therefore, multi-line


commands must be valid as a single line with the ellipsis replaced by a space character.

Examples

Continue a function call on the next line:

sprintf(['The current value '...


'of %s is %d'],vname,value)

Break a character vector up on multiple lines and concatenate the lines together:

S = ['If three or more periods occur before the '...


'end of a line, then the rest of that line is ' ...
'ignored and MATLAB continues to the next line']

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

• “Continue Long Statements on Multiple Lines” on page 1-2

2-5
2 Program Components

, Name: Comma

Uses: Separator

Description: Use commas to separate row elements in an array, array subscripts,


function input and output arguments, and commands entered on the same line.

Examples

Separate row elements to create an array:

A = [12,13; 14,15]

Separate subscripts:

A(1,2)

Separate input and output arguments in function calls:

[Y,I] = max(A,[],2)

Separate multiple commands on the same line (showing output):

figure, plot(sin(-pi:0.1:pi)), grid on

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

Create a vector that increments by 3:

x = 1:3:19

Reshape a matrix into a column vector:

A(:)

Assign new elements without changing the shape of an array:

A = rand(3,4);
A(:) = 1:12;

Index a range of elements in a particular dimension:

A(2:5,3)

Index all elements in a particular dimension:

A(:,3)

for loop bounds:

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:

• Signify end of row


• Suppress output of code line

Description: Use semicolons to separate rows in an array creation command, or to


suppress the output display of a line of code.

Examples

Separate rows to create an array:

A = [12,13; 14,15]

Suppress code output:

Y = max(A);

Separate multiple commands on a single line (suppressing output):

A = 12.5; B = 42.7, C = 1.25;


B =
42.7000

More Information

• vertcat

2-8
MATLAB Operators and Special Characters

( ) Name: Parentheses

Uses:

• Operator precedence
• Function argument enclosure
• Indexing

Description: Use parentheses to specify precedence of operations, enclose function input


arguments, and index into an array.

Examples

Precedence of operations:

(A.*(B./C)) - D

Function argument enclosure:

plot(X,Y,'r*')
C = union(A,B)

Indexing:

A(3,:)
A(1,2)
A(1:5,1)

More Information

• “Operator Precedence” on page 2-32


• “Array Indexing”

2-9
2 Program Components

[ ] Name: Square brackets

Uses:

• Array construction
• Array concatenation
• Empty matrix and array element deletion
• Multiple output argument assignment

Description: Square brackets enable array construction and concatenation, creation of


empty matrices, deletion of array elements, and capturing values returned by a function.

Examples

Construct a three-element vector:

X = [10 12 -3]

Add a new bottom row to a matrix:

A = rand(3);
A = [A; 10 20 30]

Create an empty matrix:

A = []

Delete a matrix column:

A(:,1) = []

Capture three output arguments from a function:

[C,iA,iB] = union(A,B)

More Information

• “Creating, Concatenating, and Expanding Matrices”


• horzcat
• vertcat

2-10

You might also like