Using MATLAB (779505), страница 79
Текст из файла (страница 79)
A serial daterepresents a calendar date as the number of days that has passed since a fixedbase date. In MATLAB, serial date number 1 is January 1, 0000. MATLAB alsouses serial time to represent fractions of days beginning at midnight; forexample, 6 p.m. equals 0.75 serial days. So the string '16-Sep-1996, 6:00 pm'in MATLAB is date number 729284.75.All functions that require dates accept either date strings or serial datenumbers. If you are dealing with a few dates at the MATLAB command-linelevel, date strings are more convenient. If you are using functions that handlelarge numbers of dates or doing extensive calculations with dates, you will getbetter performance if you use date numbers.Date vectors are an internal format for some MATLAB functions; you do nottypically use them in calculations.
A date vector contains the elements [yearmonth day hour minute second].MATLAB provides functions that convert date strings to serial date numbers,and vice versa. Dates can also be converted to date vectors.Here are examples of the three date formats used by MATLAB.Date FormatExampleDate string02-Oct-1996Serial date number729300Date vector1996 10 2 0 0 017-6317M-File ProgrammingConversions Between Date FormatsFunctions that convert between date formats are shown below.FunctionDescriptiondatenumConvert date string to serial date numberdatestrConvert serial date number to date stringdatevecSplit date number or date string into individualdate elementsHere are some examples of conversions from one date format to another.d1 = datenum('02-Oct-1996')d1 =729300d2 = datestr(d1+10)d2 =12-Oct-1996dv1 = datevec(d1)dv1 =19961020002000dv2 = datevec(d2)dv2 =199617-6412Dates and TimesDate String FormatsThe datenum function is important for doing date calculations efficiently.datenum takes an input string in any of several formats, with 'dd-mmm-yyyy','mm/dd/yyyy', or 'dd-mmm-yyyy, hh:mm:ss.ss' most common.
You can formup to six fields from letters and digits separated by any other characters:• The day field is an integer from 1 to 31.• The month field is either an integer from 1 to 12 or an alphabetic string withat least three characters.• The year field is a non-negative integer: if only two digits are specified, thena year 19yy is assumed; if the year is omitted, then the current year is usedas a default.• The hours, minutes, and seconds fields are optional. They are integersseparated by colons or followed by 'AM' or 'PM'.For example, if the current year is 1996, then these are all equivalent'17-May-1996''17-May-96''17-May''May 17, 1996''5/17/96''5/17'and both of these represent the same time'17-May-1996, 18:30''5/17/96/6:30 pm'Note that the default format for numbers-only input follows the Americanconvention. Thus 3/6 is March 6, not June 3.If you create a vector of input date strings, use a column vector and be sure allstrings are the same length.
Fill in with spaces or zeros.Output FormatsThe function datestr(D,dateform) converts a serial date D to one of 19different date string output formats showing date, time, or both. The defaultoutput for dates is a day-month-year string: 01-Mar-1996. You select analternative output format by using the optional integer argument dateform.17-6517M-File ProgrammingThis table shows the date string formats that corespond to each dateformvalue.17-66dateformFormatDescription001-Mar-1996 15:45:17day-month-year hour:minute:second101-Mar-1996day-month-year203/01/96month/day/year3Marmonth, three letters4Mmonth, single letter53month603/01month/day71day of month8Wedday of week, three letters9Wday of week, single letter101996year, four digits1196year, two digits12Mar96month year1315:45:17hour:minute:second1403:45:17 PMhour:minute:second AM or PM1515:45hour:minute1603:45 PMhour:minute AM or PM17Q1-96calendar quarter-year18Q1calendar quarterDates and TimesHere are some examples of converting the date March 1, 1996 to various formsusing the datestr function.d = '01-Mar-1999'd =01-Mar-1999datestr(d)ans =01-Mar-1999datestr(d, 2)ans =03/01/99datestr(d, 17)ans =Q1-99Current Date and TimeThe function date returns a string for today’s date.dateans =02-Oct-199617-6717M-File ProgrammingThe function now returns the serial date number for the current date and time.nowans =729300.71datestr(now)ans =02-Oct-1996 16:56:16datestr(floor(now))ans =02-Oct-199617-68Obtaining User InputObtaining User InputThere are three ways to obtain input from a user during M-file execution.
Youcan:• Display a prompt and obtain keyboard input.• Pause until the user presses a key.• Build a complete graphical user interface.This section covers the first two topics. The third topic is discussed in onlinedocumentation under “Creating Graphical User Interfaces”.Prompting for Keyboard InputThe input function displays a prompt and waits for a user response.
Its syntaxisn = input('prompt_string')The function displays the prompt_string, waits for keyboard input, and thenreturns the value from the keyboard. If the user inputs an expression, thefunction evaluates it and returns its value. This function is useful forimplementing menu-driven applications.input can also return user input as a string, rather than a numeric value. Toobtain string input, append 's' to the function’s argument list.name = input('Enter address: ','s');Pausing During ExecutionSome M-files benefit from pauses between execution steps. For example, thepetals.m script, shown in the “Simple Script Example” section, pausesbetween the plots it creates, allowing the user to display a plot for as long asdesired and then press a key to move to the next plot.The pause command, with no arguments, stops execution until the user pressesa key. To pause for n seconds, usepause(n)17-6917M-File ProgrammingShell Escape FunctionsIt is sometimes useful to access your own C or Fortran programs using shellescape functions.
Shell escape functions use the shell escape command ! tomake external stand-alone programs act like new MATLAB functions. A shellescape M-function is an M-file that:1 Saves the appropriate variables on disk.2 Runs an external program (which reads the data file, processes the data, andwrites the results back out to disk).3 Loads the processed file back into the workspace.For example, look at the code for garfield.m, below. This function uses anexternal function, gareqn, to find the solution to Garfield’s equation.function y = garfield(a,b,q,r)save gardata a b q r!gareqnload gardataThis M-file:1 Saves the input arguments a, b, q, and r to a MAT-file in the workspaceusing the save command.2 Uses the shell escape operator to access a C, or Fortran program calledgareqn that uses the workspace variables to perform its computation.gareqn writes its results to the gardata MAT-file.3 Loads the gardata MAT-file to obtain the results.17-70Optimizing MATLAB CodeOptimizing MATLAB CodeThis section describes techniques that often improve the execution speed andmemory management of MATLAB code:• Vectorizing loops• Preallocating ArraysMATLAB is a matrix language, which means it is designed for vector andmatrix operations.
For best performance, you should take advantage of thiswhere possible.For information on how to conserve memory and improve memory use, see thesection, “Making Efficient Use of Memory” on page 17-74.See “Improving M-File Performance - the Profiler” for information on using theMATLAB Profiler to identify which parts of your code consume the most time.Vectorizing LoopsYou can speed up your M-file code by vectorizing algorithms.
Vectorizationmeans converting for and while loops to equivalent vector or matrixoperations.A Simple ExampleHere is one way to compute the sine of 1001 values ranging from 0 to 10.i = 0;for t = 0:.01:10i = i+1;y(i) = sin(t);endA vectorized version of the same code is:t = 0:.01:10;y = sin(t);The second example executes much faster than the first and is the wayMATLAB is meant to be used. Test this on your system by creating M-filescripts that contain the code shown, then using the tic and toc commands totime the M-files.17-7117M-File ProgrammingAn Advanced Examplerepmat is an example of a function that takes advantage of vectorization. Itaccepts three input arguments: an array A, a row dimension M, and a columndimension N.repmat creates an output array that contains the elements of array A,replicated and “tiled” in an M-by-N arrangement.A = [1 2 3; 4 5 6];B = repmat(A,2,3);B =141425253636141425253636141425253636repmat uses vectorization to create the indices that place elements in theoutput array.function B = repmat(A,M,N)if nargin < 2error('Requires at least 2 inputs.')elseif nargin == 2N = M;end% Step 1 Get row and column sizes[m,n] = size(A);% Step 2 Generate vectors of indices from 1 to row/column sizemind = (1:m)';nind = (1:n)';% Step 3 Creates index matrices from vectors abovemind = mind(:,ones(1,M));nind = nind(:,ones(1,N));% Step 4 Create output arrayB = A(mind,nind);17-72Optimizing MATLAB CodeStep 1, above, obtains the row and column sizes of the input array.Step 2 creates two column vectors.















