Using MATLAB (779505), страница 78
Текст из файла (страница 78)
Inthis case, MATLAB operates on a page-by-page basis to create the storagecolumn, again appending elements columnwise.17-5117M-File ProgrammingFor example, consider a 5-by-4-by-3-by-2 array C.MATLAB displays C aspage(1,1) =12503416123735759295page(2,1) =67091210484414229525page(3,1) =22509251948150538293page(1,2) =90610804922392833637page(2,2) =72769045841888131642page(3,2) =1278317-52691026111753156MATLAB stores C as12503416123735759295670912104844142295252250925194...Subscripting and IndexingAgain, a single subscript indexes directly into this column.
For example, C(4)produces the resultans =0If you specify two subscripts (i,j) indicating row-column indices, MATLABcalculates the offset as described above. Two subscripts always access the firstpage of a multidimensional array, provided they are within the range of theoriginal array dimensions.If more than one subscript is present, all subscripts must conform to theoriginal array dimensions. For example, C(6,2) is invalid, because all pages ofC have only five rows.If you specify more than two subscripts, MATLAB extends its indexing schemeaccordingly. For example, consider four subscripts (i,j,k,l) into afour-dimensional array with size [d1 d2 d3 d4]. MATLAB calculates the offsetinto the storage column by(l–1)(d3)(d2)(d1)+(k–1)(d2)(d1)+(j–1)(d1)+iFor example, if you index the array C using subscripts (3,4,2,1), MATLABreturns the value 5 (index 38 in the storage column).In general, the offset formula for an array with dimensions [d1 d2 d3 ...
dn]using any subscripts (s1 s2 s3 ... sn) is(sn–1)(dn–1)(dn–2)...(d1)+(sn–1–1)(dn–2)...(d1)+...+(s2–1)(d1)+s1Because of this scheme, you can index an array using any number of subscripts.You can append any number of 1s to the subscript list because these termsbecome zero. For example,C(3,2,1,1,1,1,1,1)is equivalent toC(3,2)17-5317M-File ProgrammingString EvaluationString evaluation adds power and flexibility to the MATLAB language, lettingyou perform operations like executing user-supplied strings and constructingexecutable strings through concatenation of strings stored in variables.evalThe eval function evaluates a string that contains a MATLAB expression,statement, or function call.
In its simplest form, the eval syntax iseval('string')For example, this code uses eval on an expression to generate a Hilbert matrixof order n.t = '1/(i+j–1)';for i = 1:nfor j = 1:na(i,j) = eval(t);endendHere’s an example that uses eval on a statement.eval('t = clock');Constructing Strings for EvaluationYou can concatenate strings to create a complete expression for input to eval.This code shows how eval can create 10 variables named P1, P2, ...P10, and seteach of them to a different value.for i=1:10eval(['P',int2str(i),'= i.^2'])endfevalThe feval function differs from eval in that it executes a function rather thana MATLAB expression.
The function to be executed is specified in the firstargument by either a function handle or a string containing the function name.17-54String EvaluationYou can use feval and the input function to choose one of several tasks definedby M-files. This example uses function handles for the sin, cos, and logfunctions.fun = [@sin; @cos; @log];k = input('Choose function number: ');x = input('Enter value: ');feval(fun(k),x)Note Use feval rather than eval whenever possible. M-files that use fevalexecute faster and can be compiled with the MATLAB Compiler.17-5517M-File ProgrammingCommand/Function DualityMATLAB commands are statements likeloadhelpMany commands accept modifiers that specify operands.load August17.dathelp magictype rankAn alternate method of supplying the command modifiers makes them stringarguments of functions.load('August17.dat')help('magic')type('rank')This is MATLAB’s command/function duality.
Any command of the formcommand argumentcan also be written in the functional formcommand('argument')The advantage of the functional approach comes when the string argument isconstructed from other pieces. The following example processes multiple datafiles, August1.dat, August2.dat, and so on. It uses the function int2str,which converts an integer to a character string, to help build the filename.for d = 1:31s = ['August' int2str(d) '.dat']load(s)% Process the contents of the d-th fileend17-56Empty MatricesEmpty MatricesA matrix having at least one dimension equal to zero is called an empty matrix.The simplest empty matrix is 0-by-0 in size.
Examples of more complexmatrices are those of dimension 0-by-5 or 10-by-0-by-20.To create a 0-by-0 matrix, use the square bracket operators with no valuespecified.A = [];whos ANameASize0x0Bytes0Classdouble arrayYou can create empty arrays of other sizes using the zeros, ones, rand, or eyefunctions. To create a 0-by-5 matrix, for example, useE = zeros(0,5)Operating on an Empty MatrixThe basic model for empty matrices is that any operation that is defined form-by-n matrices, and that produces a result whose dimension is some functionof m and n, should still be allowed when m or n is zero. The size of the resultshould be that same function, evaluated at zero.For example, horizontal concatenationC = [A B]requires that A and B have the same number of rows. So if A is m-by-n and B ism-by-p, then C is m-by-(n+p).
This is still true if m or n or p is zero.Many operations in MATLAB produce row vectors or column vectors. It ispossible for the result to be the empty row vectorr = zeros(1,0)or the empty column vectorC = zeros(0,1)17-5717M-File ProgrammingAs with all matrices in MATLAB, you must follow the rules concerningcompatible dimensions. In the following example, an attempt to add a 1-by-3matrix to a 0-by-3 empty matrix results in an error.[1 2 3] + ones(0,3)??? Error using ==> +Matrix dimensions must agree.Some MATLAB functions, like sum and max, are reductions. For matrixarguments, these functions produce vector results; for vector arguments theyproduce scalar results. Empty inputs produce the following results with thesefunctions:• sum([ ]) is 0• prod([ ]) is 1• max([ ]) is [ ]• min([ ]) is [ ]Using Empty Matrices with If or WhileWhen the expression part of an if or while statement reduces to an emptymatrix, MATLAB evaluates the expression as being false.
The followingexample executes statement S0, because A is an empty array.A = ones(25,0,4);if AS1elseS0end17-58Errors and WarningsErrors and WarningsIn many cases, it’s desirable to take specific actions when different kinds oferrors occur. For example, you may want to prompt the user for more input,display extended error or warning information, or repeat a calculation usingdefault values. MATLAB’s error handling capabilities let your applicationcheck for particular error conditions and execute appropriate code dependingon the situation.Error Handling with eval and lasterrThe basic tools for error-handling in MATLAB are:• The eval function, which lets you execute a function and specify a secondfunction to execute if an error occurs in the first.• The lasterr function, which returns a string containing the last errorgenerated by MATLAB.The eval function provides error-handling capabilities using the twoargument formeval ('trystring','catchstring')If the operation specified by trystring executes properly, eval simply returns.If trystring generates an error, the function evaluates catchstring.
Usecatchstring to specify a function that determines the error generated bytrystring and takes appropriate action.The trystring/catchstring form of eval is especially useful in conjunctionwith the lasterr function. lasterr returns a string containing the last errormessage generated by MATLAB. Use lasterr inside the catchstring functionto “catch” the error generated by trystring.For example, this function uses lasterr to check for a specific error messagethat can occur during matrix multiplication.
The error message indicates thatmatrix multiplication is impossible because the operands have different innerdimensions. If the message occurs, the code truncates one of the matrices toperform the multiplication.function C = catchfcn(A,B)l = lasterr;j = findstr(l,'Inner matrix dimensions')17-5917M-File Programmingif (~isempty(j))[m,n] = size(A)[p,q] = size(B)if (n>p)A(:,p+1:n) = []elseif (n<p)B(n+1:p,:) = []endC = A*B;elseC = 0;endThis example uses the two-argument form of eval with the catchfcn functionshown above.clearA = [1 2 3; 6 7 2; 0 1B = [9 5 6; 0 4 9];eval('A*B','catchfcn(A,B)')5];A = 1:7;B = randn(9,9);eval('A*B','catchfcn(A,B)')Displaying Error and Warning MessagesUse the error and fprintf functions to display error information on thescreen. The error function has the syntaxerror('error string')If you call the error function from inside an M-file, error displays the text inthe quoted string and causes the M-file to stop executing.
For example, supposethe following appears inside the M-file myfile.m.if n < 1error('n must be 1 or greater.')end17-60Errors and WarningsFor n equal to 0, the following text appears on the screen and the M-file stops.??? Error using ==> myfilen must be 1 or greater.In MATLAB, warnings are similar to error messages, except programexecution does not stop. Use the warning function to display warningmessages.warning('warning string')The function lastwarn displays the last warning message issued by MATLAB.17-6117M-File ProgrammingDates and TimesMATLAB provides functions for time and date handling. These functions arein a directory called timefun in the MATLAB Toolbox.CategoryFunctionDescriptionCurrent date and timeclockCurrent date and time as date vectordateCurrent date as date stringnowCurrent date and time as serial date numberdatenumConvert to serial date numberdatestrConvert to string representation of datedatevecDate componentscalendarCalendardatetickDate formatted tick labelseomdayEnd of monthweekdayDay of the weekcputimeCPU time in secondsetimeElapsed timetic, tocStopwatch timerConversionUtilityTimingDate FormatsThis section covers the following topics:• “Types of Date Formats”• “Conversions Between Date Formats”• “Date String Formats”• “Output Formats”17-62Dates and TimesTypes of Date FormatsMATLAB works with three different date formats: date strings, serial datenumbers, and date vectors.When dealing with dates you typically work with date strings (16-Sep-1996).MATLAB works internally with serial date numbers (729284).
















