Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

MATLAB Programming/Scripts

From Wikibooks, open books for an open world
<MATLAB Programming
This page may need to bereviewed for quality.

[MATLAB Programming\|/MATLAB Programming]m]

Chapter 1: MATLAB ._.

Introductions .
Fundamentals of MATLAB
MATLAB Workspace
MATLAB Variables
*.mat files

Chapter 2: MATLAB Concepts

MATLAB operator
Data File I/O

Chapter 3: Variable Manipulation

Numbers and Booleans
Strings
Portable Functions
Complex Numbers

Chapter 4: Vector and matrices

Vector and Matrices
Special Matrices
Operation on Vectors
Operation on Matrices
Sparse Matrices

Chapter 5: Array

Arrays
Introduction to array operations
Vectors and Basic Vector Operations
Mathematics with Vectors and Matrices
Struct Arrays
Cell Arrays

Chapter 6: Graphical Plotting

Basic Graphics Commands
Plot
Polar Plot
Semilogx or Semilogy
Loglog
Bode Plot
Nichols Plot
Nyquist Plot

Chapter 7: M File Programming

Scripts
Comments
The Input Function
Control Flow
Loops and Branches
Error Messages
Debugging M Files

Chapter 8: Advanced Topics

Numerical Manipulation
Advanced File I/O
Object Oriented Programming
Applications and Examples
Toolboxes and Extensions

Chapter 9: Bonus chapters

MATLAB Benefits and Caveats
Alternatives to MATLAB
[MATLAB_Programming/GNU_Octave|What is Octave= (8) hsrmonic functions]
Octave/MATLAB differences

edit this box


M-files

[edit |edit source]

There are 2 types of m-file

  • Scripts
  • Functions

Scripts are a type of m-file that runs in the current workspace. So if you call a script from the command line (base workspace) the script will use and manipulate the variables of the base workspace. This can get very messy and lead to all sorts of strange errors when loops are involved and the coder is lazy about naming their loop variables (i.e. for i = 1:10, if every loop uses i, j, or k then it's likely that any script called from a loop will alter the loop variable).

Functions are wholly contained in themselves. They possess their own workspace keeping workspaces separate. This means that all variables necessary for a particular function must be passed or defined in some way. This can get tedious for complex algorithms requiring lots of variables. However, any manipulations of variables are discarded when the function is exited. Only those output arguments provided by the function are available to the calling workspace. This means that loops can use i, j, or k all they want because the function's workspace and the calling workspace do not mix.

Any command valid at the command line is valid in any m-file so long as the necessary variables are present in the m-files operating workspace.

Using functions properly any change can be affected to any algorithm or plotting tool. This allows for automation of repetitive tasks.

It is optional to end the M-file with 'end'; doing so, however, can lead to complications if you have conditionals or loops in your code, or if you're planning on using multiple functions in the same file (see nested functions for details on this).

Requirements for a function

[edit |edit source]

Custom functions follow this syntax in their most basic form:

function [output1, output2, ...]=function_name(input_arg1,input_arg2)statementsreturn;

In current versions of MATLAB thereturn; line is not required. Thefunction_name can be anything you like but it is best if the m-file name isfunction_name.m. Calling the function from the command line or another m-file is done by invoking the m-file name of the function with the necessary input and output arguments.

Within the function itself, there must be a statement that defines each of the output arguments (output1, output2, etc.). Without some declaration the variable for the output argument doesn't exist in the function's workspace. This will cause an error about "one or more output arguments". It is good practice to initialize the output arguments at the beginning of the function.

Typically output arguments are initialized to empty ([]) or 0 or -1 or something equivalent for other data types. The reason is that if the function encounters an error you've anticipated then the function can return (via thereturn command) with those default values. If the initialization value is an invalid value then it can easily be checked by the calling function for any errors which may not throw a MATLAB error.

Path

[edit |edit source]

In order to invoke a function, that function's m-file must be in the current path. There is a default path that can be set up through the File menu or theaddpath command. The order of the path is important as MATLAB searches the path in order and stops searching after it finds the first instance of that m-file name.

The current path is

  • the current directory (which can be seen at the top of the MATLAB window or by typingpwd at the command prompt
  • the default path

Note that MATLAB will always search the current directory before searching any of the rest of the path.

nargin & nargout

[edit |edit source]

Thenargin andnargout commands are only valid inside functions since scripts are not passed any arguments. Thenargin command returns the number of passed input arguments. This is useful in conjunction with nargchk

 nargchk(min, max, nargin)

where min is the minimum number of arguments necessary for the function to operate and max is the maximum number of valid input arguments.

Thenargout command is useful for determining which output arguments to return. Typically, the outputs are the end results of some algorithm and they are easily calculated. However, in some instances secondary output arguments can be time consuming to calculate or require more input arguments than the primary output arguments do. So the function can check the number of output arguments being requested through thenargout command. If the caller isn't saving the secondary output arguments then they do not need to be calculated.

varargin & varargout

[edit |edit source]

When using MATLAB objects and functions they often allow the user to set properties. The functions and objects come with default values for these properties but the user is allowed to override these defaults. This is accomplished through the use ofvarargin.varargin is a cell array that is usually parsed wherevarargin{i} is a property andvarargin{i+1} is the value the user wishes for that property. The parsing is done with afor orwhile loop and aswitch statement.

 function [out] = myFunc(in, varargin)

Thevarargout output argument option allows for a variable number of output arguments just asvarargin allows for a variable number of input arguments. From theMATLAB site

 function [s,varargout] = mysize(x) nout = max(nargout,1)-1; s = size(x); for k=1:nout, varargout(k) = {s(k)}; end

returns the size vector and, optionally, individual sizes. So

 [s,rows,cols] = mysize(rand(4,5));

returns s = [4 5], rows = 4, cols = 5.

Useful syntax guidelines

[edit |edit source]

Placing the semicolon symbol after every line tells the compiler not to place that line of code in the command prompt and then execute. This can make your programs run a lot faster. Also, placing a semicolon after every line helps with the debugging process.

syms x y z;w=[x y z];e=[1 2 3];t=jacobian(e,w);

Placing comments in your code can help other people (and yourself) understand your code as it gets more complex.

syms x y z;                 %syms command makes x y and z symbolicw=[x y z];e=[1 2 3];t=jacobian(e,w);

Comments can also Identify who wrote the code and when they wrote it.

%Some code writer%mm/dd/yyyy

See the 'comments' section for more details on this.

Nested functions

[edit |edit source]
Clipboard

To do:
Write stuff on nested functions, advantages and disadvantages of them


External Links

[edit |edit source]

Large parts of this page come from theControlTheoryPro.com page on M-files,Scripts, andFunctions.

Retrieved from "https://en.wikibooks.org/w/index.php?title=MATLAB_Programming/Scripts&oldid=3583157"
Category:
Hidden category:

[8]ページ先頭

©2009-2025 Movatter.jp