Input and Output in MATLAB Lecture 13: Supporting Material Dr Kathryn Merrick Tuesday 14 th April, 2009
Dec 26, 2015
Input and Output in MATLAB
Lecture 13: Supporting Material
Dr Kathryn Merrick
Tuesday 14th April, 2009
Overview
Gathering user input
Formatting output for display
File input and output
Code clichés for designing a user interface
An Introductory Problem…
Question:
At 200km/hr, what will stop in a shorter distance, a road car or a F1 race car?
From Problem to Program…
1. Understand the problem ‘in English’
2. Develop a rough solution on paper
3. Implement the solution in MATLAB
4. Test your solution
Some Equations for Motion
s is stopping distance u is initial velocity v is final velocity μ is the coefficient of friction
between tyres and road g is gravity t is time a is acceleration g
us
2
2
2
2
1atuts
t
uva
Demo 1:
Interactive Calculator for Motion in MATLAB
Gathering User Input
Numbers
time = input('Enter time in seconds: ');
Strings
name = input('Enter your name: ', 's');
Displaying Simple Output
disp('Error: You must enter a number from 1-3')
disp('Now exiting the program... Goodbye.')
disp(pi)
Demo 2:
Formatting Output
Formatting Complex Output
name = 'Kathryn';
office_number = 212;
fprintf('The lecturer''s name is %s.
Her office number is %u.\n',
name,
office_number);
Useful fprintf Options
%s string
%d decimal (scientific notation)
%f floating point number
%.2f floating point number to 2 decimal places
\n new line
\t tab
Quick Quiz: Code Clichés
Name the two code clichés used in interactive calculator for motion:
(1) Sentinel guarded loop
(2) Enumeration
Demo 3:
File I/O
File Input and Output
Input
[cartypes velocities] = textread(input_filename, '%s %f', 'delimiter', '\t');
Output
open_output_file = fopen(output_filename, 'wt');
fprintf(open_output_file, '%s velocity is %f ms-1.\n', cartype, velocity);
fclose(open_output_file);
Summary
After today’s lecture you should be able to:
Gather user input Format and display
output Input and output data
using files Design simple, text-
based user interfaces