Using MATLAB (779505), страница 75
Текст из файла (страница 75)
Theseare not requirements, but guidelines to increase the readability of MATLABcode and reduce the chance of accidentally redefining a global variable.Persistent VariablesA variable may be defined as persistent so that it does not change value fromone call to another. Persistent variables may be used within a function only.Persistent variables remain in memory until the M-file is cleared or changed.persistent is exactly like global, except that the variable name is not in theglobal workspace, and the value is reset if the M-file is changed or cleared.Three MATLAB functions support the use of persistent variables.17-20FunctionDescriptionmlockPrevents an M-file from being clearedmunlockUnlocks an M-file that had previously been locked by mlockmislockedIndicates whether an M-file can be cleared or notLocal and Global VariablesSpecial ValuesSeveral functions return important special values that you can use in yourM-files.FunctionReturn ValueansMost recent answer (variable).
If you do not assign an outputvariable to an expression, MATLAB automatically stores theresult in ans.epsFloating-point relative accuracy. This is the toleranceMATLAB uses in its calculations.realmaxLargest floating-point number your computer can represent.realminSmallest floating-point number your computer can represent.pi3.1415926535897...i, jImaginary unit.infInfinity.
Calculations like n/0, where n is any nonzero realvalue, result in inf.NaNNot-a-Number, an invalid numeric value. Expressions like 0/0and inf/inf result in a NaN, as do arithmetic operationsinvolving a NaN. n/0, where n is complex, also returns NaN.computerComputer type.versionMATLAB version string.Here are several examples that use these values in MATLAB expressions.x = 2*pi;A = [3+2i 7–8i];tol = 3*eps;17-2117M-File ProgrammingData TypesThere are 14 fundamental data types (or classes) in MATLAB.
Each of thesedata types is in the form of an array. This array is a minimum of 0-by-0 in sizeand can grow to an n-dimensional array of any size. Two-dimensional versionsof these arrays are called matrices.All of the fundamental data types are shown in lowercase text in the diagrambelow. An additional, user-defined data type, shown below as user class, is asubset of the structure type.ARRAYcharNUMERICcellstructureuser classint8, uint8,int16, uint16,int32, uint32singlefunction handlejava classdoublesparseThe char data type holds characters in Unicode representation. A characterstring is merely a 1-by-n array of characters.
You can use char to hold an arrayof strings as long as each string in the array has the same length. (This isbecause MATLAB arrays must be rectangular.) To hold an array of strings ofunequal length, use a cell array.Numeric data types include signed and unsigned integers, single- and doubleprecision floating point, and sparse matrices of double-precision. The followinghold true for numeric data types in MATLAB:• All MATLAB computations are done in double-precision.• Integer and single precision arrays offer more memory efficient storage thandouble-precision.• All data types support basic array operations, such as subscripting andreshaping.17-22Data Types• To perform mathematical operations on integer or single precision arrays,you must convert them to double precision using the double function.A cell array provides a storage mechanism for dissimilar kinds of data.
Youcan store arrays of different types and/or sizes within the cells of a cell array.For example, you can store a 1-by-50 char array, a 7-by-13 double array, anda 1-by-1 uint32 in cells of the same cell array. You access data in a cell arrayusing the same matrix indexing used on other MATLAB matrices and arrays.The MATLAB structure data type is similar to the cell array in that it alsostores dissimilar kinds of data. But, in this case, it stores the data in namedfields rather than in cells. This enables you to attach a name to the groups ofdata stored within the structure. You access data in a structure using thesesame field names.MATLAB data types are implemented as classes.
You can also create MATLABclasses of your own. These user-defined classes inherit from the MATLABstructure class and are shown in the previous diagram as a subset ofstructure.MATLAB provides an interface to the Java programming language thatenables you to create objects from Java classes and call Java methods on theseobjects. A Java class is a MATLAB data type.
There are built-in and third-partyclasses that are already available through the MATLAB interface. You can alsocreate your own Java class definitions and bring them into MATLAB.A function handle holds information to be used in referencing a function.When you create a function handle, MATLAB captures all the informationabout the function that it needs to locate and execute, or evaluate, it later on.Typically, a function handle is passed in an argument list to other functions. Itis then used in conjunction with feval to evaluate the function to which thehandle belongs.The following table describes the data types in more detail.Data TypeExampleDescriptionsingle3*10^38Single-precision numeric array.
Single precisionrequires less storage than double precision, buthas less precision and a smaller range. This datatype cannot be used in mathematical operations.17-2317M-File Programming17-24Data TypeExampleDescriptiondouble3*10^3005+6iDouble-precision numeric array. This is the mostcommon MATLAB variable type.sparsespeye(5)Sparse double-precision matrix (2-D only). Thesparse matrix stores matrices with only a fewnonzero elements in a fraction of the spacerequired for an equivalent full matrix. Sparsematrices invoke special methods especiallytailored to solve sparse problems.int8, uint8,int16, uint16,int32, uint32uint8(magic(3))Signed and unsigned integer arrays that are8, 16, and 32 bits in length.
Enables you tomanipulate integer quantities in a memoryefficient manner. These data types cannot be usedin mathematical operations.char'Hello'Character array (each character is 16 bits long).This array is also referred to as a string.cell{17 'hello' eye(2)}Cell array. Elements of cell arrays contain otherarrays. Cell arrays collect related data andinformation of a dissimilar size together.structurea.day = 12;a.color = 'Red';a.mat = magic(3);Structure array. Structure arrays have fieldnames. The fields contain other arrays. Like cellarrays, structures collect related data andinformation together.user classinline('sin(x)')MATLAB class.
This user-defined class is createdusing MATLAB functions.java classjava.awt.FrameJava class. You can use classes already defined inthe Java API or by a third party, or create yourown classes in the Java language.function handle@humpsHandle to a MATLAB function. A function handlecan be passed in an argument list and evaluatedusing feval.KeywordsKeywordsMATLAB reserves certain words for its own use as keywords of the language.To list the keywords, typeiskeywordans ='break''case''catch''continue''else''elseif''end''for''function''global''if''otherwise''persistent''return''switch''try''while'See the online function reference pages for help to learn how to use any of thesekeywords.You should not use MATLAB keywords other than for their intended purpose.For example, a keyword should not be used as follows:while = 5;??? while = 5;|Error: Expected a variable, function, or constant, found "=".17-2517M-File ProgrammingOperatorsMATLAB’s operators fall into three categories:• Arithmetic operators that perform numeric computations, for example,adding two numbers or raising the elements of an array to a given power.• Relational operators that compare operands quantitatively, using operatorslike “less than” and “not equal to.”• Logical operators that use the logical operators AND, OR, and NOT.This section also discusses operator precedence.Arithmetic OperatorsMATLAB provides these arithmetic operators17-26OperatorDescription+Addition–Subtraction.*Multiplication./Right division.\Left division+Unary plus–Unary minus:Colon operator.^Power.'Transpose'Complex conjugate transpose*Matrix multiplication/Matrix right divisionOperatorsOperatorDescription\Matrix left division^Matrix powerArithmetic Operators and ArraysExcept for some matrix operators, MATLAB’s arithmetic operators work oncorresponding elements of arrays with equal dimensions.
For vectors andrectangular arrays, both operands must be the same size unless one is a scalar.If one operand is a scalar and the other is not, MATLAB applies the scalar toevery element of the other operand – this property is known as scalarexpansion.This example uses scalar expansion to compute the product of a scalar operandand a matrix.A = magic(3)A =83415967231527182163 * Aans =2491217-2717M-File ProgrammingRelational OperatorsMATLAB provides these relational operators.OperatorDescription<Less than<=Less than or equal to>Greater than>=Greater than or equal to==Equal to~=Not equal toRelational Operators and ArraysMATLAB’s relational operators compare corresponding elements of arrayswith equal dimensions.















