Page 92 - Basics of MATLAB and Beyond
P. 92
Examples:
sprintf(’%0.5g’,(1+sqrt(5))/2) 1.618
sprintf(’%0.5g’,1/eps) 4.5036e+15
sprintf(’%10.3f’,-pi) -3.142
sprintf(’%10.3f’,-pi*1000000) -3141592.654
sprintf(’%10.3f’,-pi/1000000) -0.000
sprintf(’%d’,round(pi)) 3
sprintf(’%s’,’hello’) hello
sprintf(’The array is %dx%d.’,2,3) The array is 2x3.
sprintf(’\n’) Line termination char-
acter on all platforms
These functions are “vectorised”, meaning that if you input a non-
scalar, then all the elements will be converted:
>> str = num2str(rand(3,3),6)
str =
0.5028130.304617 0.682223
0.709471 0.189654 0.302764
0.428892 0.193431 0.541674
>> size(str)
ans =
332
Exercise 9 Explore the operation of the following m-file that
breaks a sentence up into a list of words.
function all_words = words(input_string)
remainder = input_string;
all_words = ’’;
while any(remainder)
[chopped,remainder] = strtok(remainder);
all_words = strvcat(all_words,chopped);
end
Why do you think strvcat is used instead of char? (Answer on
page 188.)
26.5 Using Strings as Commands
The eval Function
The eval function takes a string input and executes it as a matlab
command. For example:
>> str = ’v = 1:5’
str =
v = 1:5
c 2000 by CRC Press LLC