Brief IO examples ------------------------------------------------------------------------------- Automatic output: MATLAB will show an expression's value if you do not suppress the output >> 1 + 1 ans = 2 Steps: - MATLAB adds 1 and 1 and stores the result in builtin variable $ans$ - MATLAB reports the output >> x = 1 + 2 x = 3 Steps: - MATLAB adds 1 and 2 and stores the result in x - MATLAB reports the value of x ------------------------------------------------------------------------------- Displaying strings: + use the DISP function for displaying an array of strings: disp(string) --> output a string disp([string1, string2, ...]) --> concatenate the strings and output the result >> disp(['a ',' b ',' c']); + use num2string(number) to convert a number to a string (very useful for DISP!) >> value = 2; >> disp(['The answer is: ',num2str(value)]); ------------------------------------------------------------------------------- Getting input: + from user, use INPUT: value=input('prompt'); value=input('prompt','s'); ex) >> value = input('Enter a number: '); ex) >> value = input('Enter a string: ','s'); ------------------------------------------------------------------------------- Example: % Get initial input from the user: value = str2double(input(prompt,'s')); % Ensure that the input is legal: while ~isreal(value) | ... % no complex numbers isinf(value) | ... % no infinite values isnan(value) | ... % no NaNs ~isnumeric(value) | ... % no non-numerical values floor(value)~=ceil(value) | ... % no decimal/fraction values value < -realmax | ... % lower bound of integer value > realmax % upper bound of integer % Reprompt the user and get revised input: disp('That value is not an integer!'); value = str2double(input(prompt,'s')); end -------------------------------------------------------------------------------