Graphics Programs Reference
In-Depth Information
Further increases in speed can be achieved by pre-allocating the output
matrix y . If we have an m-file called factorialpre.m :
y = zeros (1,500);
for number = 1:500
y(number) = prod(1:number);
end
the execution time is about 10% faster: 4
>> clear
>> tic;factorialpre;toc
elapsed_time =
0.3752
More on vectorising code is given in Part II (see page 175).
8.4 Comparing Strings
The tests in flow control statements often involve strings (arrays of char-
acters). For example you may want to ask the user of an m-file a ques-
tion which has a “yes” or “no” response, and adjust the flow accordingly.
Although matlab has sophisticated menu utilities, the following is often
su2cient 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, rather
than a numerical response. The following matlab code tests for a 'y'
response:
if strcmp(lower(ans(1)),'y')
go_ahead
else
return
end
The strcmp function compares strings, lower converts to lower-case
characters and ans(1) selects the first letter of the response. Type
help strcmp for more information. The return command returns to
the invoking function or to the matlab prompt.
9 Data Files
Many techniques are available to read data into matlab and to save data
from matlab. The load and save functions can load or save matlab
format binary or plain ASCII files, and low-level input-output routines
can be used for other format s.
4 See matlab's gamma function if you are interested in computing factorials.
Search WWH ::




Custom Search