12.07.2015 Views

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

Basics of MATLAB and Beyond

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Further increases in speed can be achieved by pre-allocating the outputmatrix y. If we have an m-file called factorialpre.m:y = zeros (1,500);for number = 1:500y(number) = prod(1:number);endthe execution time is about 10% faster: 4>> clear>> tic;factorialpre;tocelapsed_time =0.3752More on vectorising code is given in Part II (see page 175).8.4 Comparing StringsThe tests in flow control statements <strong>of</strong>ten involve strings (arrays <strong>of</strong> characters).For example you may want to ask the user <strong>of</strong> an m-file a questionwhich has a “yes” or “no” response, <strong>and</strong> adjust the flow accordingly.Although matlab has sophisticated menu utilities, the following is <strong>of</strong>tensufficient to get a user input:input(’Do you want to continue (y or n) ? ’,’s’);The ’s’ at the end tells matlab to expect a string response, ratherthan a numerical response. The following matlab code tests for a ‘y’response:if strcmp(lower(ans(1)),’y’)go_aheadelsereturnendThe strcmp function compares strings, lower converts to lower-casecharacters <strong>and</strong> ans(1) selects the first letter <strong>of</strong> the response. Typehelp strcmp for more information. The return comm<strong>and</strong> returns tothe invoking function or to the matlab prompt.9 Data FilesMany techniques are available to read data into matlab <strong>and</strong> to save datafrom matlab. The load <strong>and</strong> save functions can load or save matlabformat binary or plain ASCII files, <strong>and</strong> low-level input-output routinescan be used for other formats.4 See matlab’s gamma function if you are interested in computing factorials.c○ 2000 by CRC Press LLC

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!