Command And Function Syntax - NTNU

2y ago
25 Views
2 Downloads
302.03 KB
15 Pages
Last View : 13d ago
Last Download : 3m ago
Upload by : Anton Mixon
Transcription

Command and Function SyntaxCommand and Function SyntaxThis section covers the following topics: “Syntax Help” “Command and Function Syntaxes” “Command Line Continuation” “Completing Commands Using the Tab Key” “Recalling Commands” “Clearing Commands” “Suppressing Output to the Screen”Syntax HelpFor help about the general syntax of MATLAB functions and commands, typehelp syntaxCommand and Function SyntaxesYou can enter MATLAB commands using either a command or function syntax.It is important to learn the restrictions and interpretation rules for both.functionname arg1 arg2 arg3functionname('arg1','arg2','arg3')% Command syntax% Function syntaxFor more information: See “Calling Functions” in the MATLAB“Programming and Data Types” documentationCommand Line ContinuationYou can continue most statements to one or more additional lines byterminating each incomplete line with an ellipsis (.). Breaking down astatement into a number of lines can sometimes result in a clearerprogramming style.sprintf ('Example %d shows a command coded on %d lines.\n', .example number, .number of lines)3

MATLAB Programming TipsNote that you cannot continue an incomplete string to another line.disp 'This statement attempts to continue a string .to another line, resulting in an error.'For more information: See “Entering Long Lines” in the MATLAB“Development Environment” documentationCompleting Commands Using the Tab KeyYou can save some typing when entering commands by entering only the firstfew letters of the command, variable, property, etc. followed by the Tab key.Typing the second line below (with T representing Tab) yields the expanded,full command shown in the third line:f figure;set(f, 'papTuT,'cT)set(f, 'paperunits','centimeters')% Type this line.% This is what you get.If there are too many matches for the string you are trying to complete, you willget no response from the first Tab. Press Tab again to see all possible choices:set(f, ePaperSizePaperTypePaperUnitsParentFor more information: See “Tab Completion” in the MATLAB “DevelopmentEnvironment” documentationRecalling CommandsUse any of the following methods to simplify recalling previous commands tothe screen: To recall an earlier command to the screen, press the up arrow key one ormore times, until you see the command you want. If you want to modify therecalled command, you can edit its text before pressing Enter or Return toexecute it. To recall a specific command by name without having to scroll through yourearlier commands one by one, type the starting letters of the command,followed by the up arrow key.4

Command and Function Syntax Open the Command History window (View - Command History) to see allprevious commands. Double-click on the one you want to execute.For more information: See “Recalling Previous Lines,” and “CommandHistory” in the MATLAB “Development Environment” documentationClearing CommandsIf you have typed a command that you then decide not to execute, you can clearit from the Command Window by pressing the Escape (Esc) key.Suppressing Output to the ScreenTo suppress output to the screen, end statements with a semicolon. This can beparticularly useful when generating large matrices.A magic(100);% Create matrix A, but do not display it.5

HelpWriting Your Own HelpStart each program you write with a section of text providing help on how andwhen to use the function. If formatted properly, the MATLAB help functiondisplays this text when you enterhelp functionname MATLAB considers the first group of consecutive lines immediately followingthe function definition line that begin with % to be the help section for thefunction. The first line without % as the left-most character ends the help.For more information: See “Help Text” in the MATLAB “DevelopmentEnvironment” documentationHelp for Subfunctions and Private FunctionsYou can write help for subfunctions using the same rules that apply to mainfunctions. To display the help for the subfunction mysubfun in file myfun.m,type:help myfun/mysubfunTo display the help for a private function, precede the function name withprivate/. To get help on private function myprivfun, type:help private/myprivfunHelp for Methods and Overloaded FunctionsYou can write help text for object-oriented class methods implemented withM-files. Display help for the method by typinghelp classname/methodnamewhere the file methodname.m resides in subdirectory @classname.For example, if you write a plot method for a class named polynom, (where theplot method is defined in the file @polynom/plot.m), you can display this helpby typinghelp polynom/plot9

M-File FunctionsM-File FunctionsThis section covers the following topics: “M-File Structure” “Using Lowercase for Function Names” “Getting a Function’s Name and Path” “What M-Files Does a Function Use?” “Dependent Functions, Built-Ins, Classes”M-File StructureAn M-File consists of the components shown here:function [x, y] myfun(a, b, c)Function definition line% H1 LineA one-line summary of the function's purpose.% Help TextOne or more lines of help text that explain%how to use the function. This text is displayed when%the user types "help functionname ".% The Function Body normally starts after the first blank line.% CommentsDescription (for internal use) of what the function%does, what inputs are expected, what outputs are generated.%Typing "help functionname " does not display this text.x prod(a, b);% Start of Function CodeFor more information: See “Basic Parts of a Function M-file” in the MATLAB“Programming and Data Types” documentationUsing Lowercase for Function NamesFunction names appear in uppercase in MATLAB help text only to make thehelp easier to read. In practice, however, it is usually best to use lowercasewhen calling functions.13

MATLAB Programming TipsFunction ArgumentsThis section covers the following topics: “Getting the Input and Output Arguments” “Variable Numbers of Arguments” “String or Numeric Arguments” “Passing Arguments in a Structure” “Passing Arguments in a Cell Array”Getting the Input and Output ArgumentsUse nargin and nargout to determine the number of input and outputarguments in a particular function call. Use nargchk and nargoutchk to verifythat your function is called with the required number of input and outputarguments.function [x, y] myplot(a, b, c, d)disp(nargchk(2, 4, nargin))disp(nargoutchk(0, 2, nargout))% Allow 2 to 4 inputs% Allow 0 to 2 outputsx plot(a, b);if nargin 4y myfun(c, d);endVariable Numbers of ArgumentsYou can call functions with fewer input and output arguments than you havespecified in the function definition, but not more. If you want to call a functionwith a variable number of arguments, use the varargin and varargoutfunction parameters in the function definition.This function returns the size vector and, optionally, individual dimensions:function [s, varargout] mysize(x)nout max(nargout, 1) - 1;s size(x);for k 1:noutvarargout(k) {s(k)};end16

Function ArgumentsTry calling it with[s, rows, cols] mysize(rand(4, 5))String or Numeric ArgumentsIf you are passing only string arguments into a function, you can use MATLABcommand syntax. All arguments entered in command syntax are interpretedas strings.strcmp string1 string1ans 1When passing numeric arguments, it is best to use function syntax unless youwant the number passed as a string. The right-hand example below passes thenumber 75 as the string, '75'.isnumeric(75)ans 1isnumeric 75ans 0For more information: See “Passing Arguments” in the MATLAB“Programming and Data Types” documentationPassing Arguments in a StructureInstead of requiring an additional argument for every value you want to passin a function call, you can package them in a MATLAB structure and pass thestructure. Make each input you want to pass a separate field in the structureargument, using descriptive names for the fields.Structures allow you to change the number, contents, or order of the argumentswithout having to modify the function. They can also be useful when you havea number of functions that need similar information.Passing Arguments in a Cell ArrayYou can also group arguments into cell arrays. The disadvantage overstructures is that you don't have fieldnames to describe each variable. Theadvantage is that cell arrays are referenced by index, allowing you to loopthrough a cell array and access each argument passed in or out of the function.17

MATLAB Programming TipsProgram DevelopmentThis section covers the following topics: “Planning the Program” “Using Pseudo-Code” “Selecting the Right Data Structures” “General Coding Practices” “Naming a Function Uniquely” “The Importance of Comments” “Coding in Steps” “Making Modifications in Steps” “Functions with One Calling Function” “Testing the Final Program”Planning the ProgramWhen planning how to write a program, take the problem you are trying tosolve and break it down into a series of smaller, independent tasks. Implementeach task as a separate function. Try to keep functions fairly short, each havinga single purpose.Using Pseudo-CodeYou may find it helpful to write the initial draft of your program in a structuredformat using your own natural language. This pseudo-code is often easier tothink through, review, and modify than using a formal programming language,yet it is easily translated into a programming language in the next stage ofdevelopment.Selecting the Right Data StructuresLook at what data types and data structures are available to you in MATLABand determine which of those best fit your needs in storing and passing yourdata.For more information: See “Data Types” in the MATLAB “Programming andData Types” documentation18

Program DevelopmentGeneral Coding PracticesA few suggested programming practices: Use descriptive function and variable names to make your code easier tounderstand. Order subfunctions alphabetically in an M-file to make them easier to find. Precede each subfunction with a block of help text describing what thatsubfunction does. This not only explains the subfunctions, but also helps tovisually separate them. Don’t extend lines of code beyond the 80th column. Otherwise, it will be hardto read when you print it out. Use full Handle Graphics property and value names. Abbreviated namesare often allowed, but can make your code unreadable. They also could beincompatible in future releases of MATLAB.Naming a Function UniquelyTo avoid choosing a name for a new function that might conflict with a namealready in use, check for any occurrences of the name using this command:which -all functionname For more information: See the which function reference pageThe Importance of CommentsBe sure to document your programs well to make it easier for you or someoneelse to maintain them. Add comments generously, explaining each majorsection and any smaller segments of code that are not obvious. You can add ablock of comments as shown ------------------% This function computes the . and so on --------------For more information: See “Comments” in the MATLAB “Programming andData Types” documentation19

MATLAB Programming TipsCoding in StepsDon't try to write the entire program all at once. Write a portion of it, and thentest that piece out. When you have that part working the way you want, thenwrite the next piece, and so on. It's much easier to find programming errors ina small piece of code than in a large program.Making Modifications in StepsWhen making modifications to a working program, don't make widespreadchanges all at one time. It's better to make a few small changes, test and debug,make a few more changes, and so on. Tracking down a difficult bug in the smallsection that you've changed is much easier than trying to find it in a huge blockof new code.Functions with One Calling FunctionIf you have a function that is called by only one other function, put it in thesame M-file as the calling function, making it a subfunction.For more information: See “Subfunctions” in the MATLAB “Programmingand Data Types” documentationTesting the Final ProgramOne suggested practice for testing a new program is to step through theprogram in the MATLAB debugger while keeping a record of each line that getsexecuted on a printed copy of the program. Use different combinations of inputsuntil you have observed that every line of code is executed at least once.20

VariablesVariablesThis section covers the following topics: “Rules for Variable Names” “Making Sure Variable Names Are Valid” “Don’t Use Function Names for Variables” “Checking for Reserved Keywords” “Avoid Using i and j for Variables” “Avoid Overwriting Variables in Scripts” “Persistent Variables” “Protecting Persistent Variables” “Global Variables”Rules for Variable NamesAlthough variable names can be of any length, MATLAB uses only the first Ncharacters of the name, (where N is the number returned by the functionnamelengthmax), and ignores the rest. Hence, it is important to make eachvariable name unique in the first N characters to enable MATLAB todistinguish variables. Also note that variable names are case-sensitive.N namelengthmaxN 63For more information: See “Naming Variables” in the MATLAB“Programming and Data Types” documentationMaking Sure Variable Names Are ValidBefore using a new variable name, you can check to see if it is valid with theisvarname function. Note that isvarname does not consider names longer thannamelengthmax characters to be valid.25

MATLAB Programming TipsFor example, the following name cannot be used for a variable since it beginswith a number.isvarname 8th columnans 0For more information: See “Naming Variables” in the MATLAB“Programming and Data Types” documentationDon’t Use Function Names for VariablesWhen naming a variable, make sure you are not using a name that is alreadyused as a function name. If you define a variable with a function name, youwon’t be able to call that function until you either clear the variable frommemory, (unless you execute the function using builtin).To test whether a proposed variable name is already used as a function name,typewhich -all name Checking for Reserved KeywordsMATLAB reserves certain keywords for its own use and does not allow you tooverride them. Attempts to use these words may result in any one of a numberof error messages, some of which are shown here:Error:Error:Error:Error:Expected a variable, function, or constant, found " "."End of Input" expected, "case" found.Missing operator, comma, or semicolon."identifier" expected, " " found.Use the iskeyword function with no input arguments to list all reserved words.Avoid Using i and j for VariablesMATLAB uses the characters i and j to represent imaginary units. Avoidusing i and j for variable names if you intend to use them in complexarithmetic.If you want to create a complex number without using i and j, you can use thecomplex function.26

VariablesAvoid Overwriting Variables in ScriptsMATLAB scripts store their variables in a workspace that is shared with thecaller of the script. When called from the command line, they share the baseworkspace. When called from a function, they share that function's workspace.If you run a script that alters a variable that already exists in the caller’sworkspace, that variable is overwritten by the script.For more information: See “Scripts” in the MATLAB “Programming andData Types” documentationPersistent VariablesTo get the equivalent of a static variable in MATLAB, use persistent. Whenyou declare a variable to be persistent within a function, its value is retainedin memory between calls to that function. Unlike global variables, persistentvariables are known only to the function in which they are declared.For more information: See “Persistent Variables” in the MATLAB“Programming and Data Types” documentationProtecting Persistent VariablesYou can inadvertently clear persistent variables from memory by eithermodifying the function in which the variables are defined, or by clearing thefunction with one of the following commands:clear allclear functionsLocking the M-file in memory with mlock prevents any persistent variablesdefined in the file from being reinitialized.Global VariablesUse global variables sparingly. The global workspace is shared by all of yourfunctions and also by your interactive MATLAB session. The more globalvariables you use, the greater the chances of unintentionally reusing a variablename, thus leaving yourself open to having those variables change in valueunexpectedly. This can be a difficult bug to track down.For more information: See “Global Variables” in the MATLAB“Programming and Data Types” documentation27

MATLAB Programming TipsStringsThis section covers the following topics: “Creating Strings with Concatenation” “Comparing Methods of Concatenation” “Store Arrays of Strings in a Cell Array” “Search and Replace Using Regular Expressions” “Converting Between Strings and Cell Arrays”Creating Strings with ConcatenationStrings are often created by concatenating smaller elements together (e.g.,strings, values, etc.). Two common methods of concatenating are to use theMATLAB concatenation operator ([]) or the sprintf function. The second andthird line below illustrate both of these methods. Both lines give the sameresult:num chars 28;s ['There are ' int2str(num chars) ' characters here']s sprintf('There are %d characters here\n', num chars)For more information: See “Creating Character Arrays,” and“Numeric/String Conversion” in the MATLAB “Programming and Data Types”documentationComparing Methods of ConcatenationWhen building strings with concatenation, sprintf is often preferable to []because It is easier to read, especially when forming complicated expressions It gives you more control over the output format It often executes more quicklyYou can also concatenate using the strcat function, However, for simpleconcatenations, sprintf and [] are faster.28

MATLAB Programming TipsTopical HelpIn addition to the help on individual functions, you can get help on any of thefollowing topics by typing help topicname at the command line.Topic NameDescriptionarithArithmetic operatorsrelopRelational and logical operatorspunctSpecial character operatorsslashArithmetic division operatorsparenParentheses, braces, and bracket operatorsprecedenceOperator precedencelistsComma separated listsstringsCharacter stringsfunction handleFunction handles and the @ operatordebugDebugging functionsjavaUsing Java from within MATLABfileformatsA list of readable file formatschange notificationWindows directory change notificationPaged OutputBefore displaying a lengthy section of help text or code, put MATLAB into itspaged output mode by typing more on. This breaks up any ensuing display intopages for easier viewing. Turn off paged output with more off.Page through the displayed text using the space bar key. Or step through lineby line using Enter or Return. Discontinue the display by pressing the Q keyor Ctrl C.8

MATLAB Programming Tips 16 Function Arguments This section covers the following topics: “Getting the Input and Output Arguments” “Variable Numbers of Arguments” “String or Numeric Arguments” “Passing Arguments in a Structure” “Passing Arguments in a Cell Array” Getting the Input and Output Arguments Use na

Related Documents:

Command Library - String Operation Command Command Library - XML Command Command Library - Terminal Emulator Command (Per Customer Interest) Command Library - PDF Integration Command Command Library - FTP Command (Per Customer Interest) Command Library - PGP Command Command Library - Object Cloning

Wireless Connection DSU/CSU Command Syntax Conventions The conventions used to present command syntax in this book are the same conven-tions used in the IOS Command Reference. The Command Reference describes these conventions as follows: Boldface indicates commands and keywords that are entered literally, as shown. In actual configuration examples and output (not general command syntax .

Other Shortcut Keys 28 Command Line Reference 30 Information for DaRT Notes Users 32 . Open command 39 Save command 39 Save As command 39 Close command 39 Recent Files command 39 Clear MRU List command 40 Remove Obsolete command 40 Auto Save command 40 Properties comman

Type the desired command or the command‟s alias at the command prompt. Command : LINE Command: L 2. Press ENTER on the keyboard. 3. Type an option at the command prompt. TIP: Many AutoCAD commands require you to press ENTER to complete the command. You know you are no longer in an AutoCAD command when you see a blank command line.

A command is a single line of syntax composed of two main parts. The most important part is the command itself, or the command word. Most command words are short and straightforward (for example, do, exit, or configure). Command words are entered immediately after the command prompt in the CLI. The second part of a command is its argument.

A spin-off from the NTNU Center for Integrated operations 07.12.2015 Proprietary to Solution Seeker 2 Solution Seeker AS is a spin-off from the world leading NTNU Center for Integrated Operations (IO Center) and an internationally outstanding ICT research group at NTNU Engi

Salford Predictive Modeler Command Reference 3 Getting Started This guide provides a command language reference and syntax. SPM has two alternative modes of control in, command-line and batch. For users running SPM in these modes, knowing the proper command syntax is a must. This guide contains a detailed description of the

1. Launch an instance of SPSS 19 a. At the top-left, click File Open Syntax i. Find you your syntax file, and click [Open] 1. Diabetes_Student.sps is for you to type and/or paste syntax into as you follow along a. Open this one for good practice 2. Diabetes_Workbook.sps is the master file containing all of the correct syntax ii.