ENGG1801_Engineering Computing_2013 summer course_lecture_8_1_1pp
- 格式:pdf
- 大小:72.72 KB
- 文档页数:40
Lecture 8-1
Text & File I/O
Summer School, 2013
School of Information Technologies
The University of Sydney, Australia
.au/~engg1801
engg1801help@.au
Jason Chan
j.chan@.au
ENGG1801 Engineering Computing 1
Day Date (Jan 2013)Lecture topics Assessment
1Fri 4Introduction, Part 1: Excel–Basics
2Sat 5Functions, Plotting, Solving equations, File I/O
Sun 6---
3Mon 7Matrix algebra Lab Exam 1 (10%) [9-10am] 4Tue 8Part 2: Matlab–Basics, If statements, Arrays
5Wed 9Loops
6Thu 10Functions (1)
7Fri 11Functions (2)
8Sat 12Text & File I/O, Character strings Lab Exam 2 (15%) [9-11am] Sun 13---
9Mon 142-D and 3-D plotting, Surface plots
10Tue 15Creating movies from matrices, Matrix algebra
11Wed 16Matrix algebra, Interpolation and curve fitting
12Thu 17Polynomial regression, Images
13Fri 18Help for the Final Exam Lab Exam 3 (25%) [9-11am] Sat 19 –Sun 20---
Exam Mon 21---Final Exam (50%)
ENGG1801 Engineering Computing
2
•I/O (Input / Output)
–How to your program to read data and also
write data
•To and from files
•To screen
•From the keyboard (typed by user)
3
ENGG1801 Engineering Computing
•File I/O(File Input/Output) is about:–How an output file is created by a program
–How an input file can be read (imported) by a
program
•Text I/O is about:
–How text output data can be displayed on a
screen
–How input data can be read from the terminal
(typed on a keyboard) by a program
4
ENGG1801 Engineering Computing
•The save command saves variables in the workspace into a binary file
–By default, all variables are saved into the
filename matlab.mat
save roots.mat x1 x2
•This example saves only variables x1and x2 into the file named roots.mat
–Other variables like disc will not be saved
5
ENGG1801 Engineering Computing
•The load command loads variables into the workspace from a file that was created using the save command
–Old variables with the same name will have
their old values replaced
load roots.mat
•This example loads into the workspace all variables that were saved into the file roots.mat
6
ENGG1801 Engineering Computing
load roots.mat x1
•This example loads only variable x1into the workspace from the file roots.mat
–If a variable x1already existed, its old value
will be replaced
7
ENGG1801 Engineering Computing
•The dlmread function reads from a given filename and returns an array containing the values in the file
–Each value is separated by a symbol called
the delimiter
–dlmread guesses what the delimiter is
8
ENGG1801 Engineering Computing
•Suppose the file input_data.txt looks like this:
12
24
36
48
•In this example, the delimiter is the tab
9
ENGG1801 Engineering Computing
% Read from file ‘input_data.txt’, and
% store into the array ‘data’
data = dlmread(‘input_data.txt’);
% Now we can use ‘data’ just like how % we can use any array, e.g. this code % prints 6
disp(data(3,2));
10
ENGG1801 Engineering Computing
•The csvread function is the same as dlmread, but assumes the file is in CSV format (lecture 2-2, slide 21-22)
–The delimiter is the comma
–Cannot handle some CSV files, e.g. with
double quotes
•There are many other similar functions for file input and output on next slide
–Use the help feature (lecture 4-1, slide 47)
11
ENGG1801 Engineering Computing
12ENGG1801 Engineering Computing File type
Filename extension Function to read Function to write Plain text
(any)textscan fprintf Comma-
separated .csv csvread
csvwrite Delimited text (e.g. tab).tab, .dlm dlmread
dlmwrite Excel .xls xlsread
xlswrite Image data (many types)imread
imwrite XML .xml xmlread xmlwrite
•Using the reading functions with just 1 parameter reads the data into a matrix •But a matrix can only have 1 type of data (e.g. numbers only)
–Use help to find out how to read only some
rows and columns
–Numbers would have to be read into one
matrix, text data into another matrix, etc.
13
ENGG1801 Engineering Computing
% Create a matrix to be written to file data = [1 2 3; 4 5 6];
% Write the above matrix to file csvwrite(‘matrix.csv’, data);
14
ENGG1801 Engineering Computing
•After running the code on the previous slide, the file matrix.csv will look like this 1,2,3
4,5,6
•And since it is a CSV file, you can open it with Excel!
15
ENGG1801 Engineering Computing
•Files are saved into or read from the
current working directory (folder)
•Check what the current working directory is with pwd (print working directory)
ENGG1801 Engineering Computing
16
•Change the working directory with the cd command, e.g.
–Change to (goes into) the directory lab5that is inside the current working directory –Change to the parent directory (gets out of
the current directory)
•Note the space between
cd and ..
ENGG1801 Engineering Computing
17
•We can read user input (from keyboard): % Ask the user for a number. The program will
% pause on this line until the user presses Enter.
% Whatever they typed on that line will be stored
% in the variable ‘number’
number = input(‘Enter a number to be doubled: ’);
% Use the variable containing the data that the
% user typed
number = number * 2;
disp(number);
18
ENGG1801 Engineering Computing
•Warning:You should always use meaningful messages with the input function!
–Otherwise, the user may wait for the program
while the program waits for the user
19
ENGG1801 Engineering Computing
•Given the following code:
% An array storing many marks
marks = [73 42 58 90 84 21];
•Q1)Use a while loop to write code that will print out each mark
•Q2)Q1, but use a for loop instead
•Q3)Write code that finds the total marks •Q4)Q3, but only count passing students
20
ENGG1801 Engineering Computing
•See lecture 5-2 for more details
% ‘i’ is the index (position) in the array we are up to i= 1;
% Go through each mark
while i<= length(marks)
% Print the current (i’th) element in marks
disp(marks(i));
% Get ready to go to the next mark
i= i+ 1;
end
ENGG1801 Engineering Computing
21
% Go through each mark.
% ‘m’ will be one of the different marks in the ‘marks’% array on each iteration of the loop
for m = marks
% Print the current mark
disp(m);
end
ENGG1801 Engineering Computing
22
% This variable will store the current total of marks % that we have seen so far
total = 0;
% Go through each mark
for m = marks
% Add to the total the current mark
total = total + m;
end
% Print total to screen
disp(total);
ENGG1801 Engineering Computing
23
% Store current total of marks that we have seen so far total = 0;
% Go through each mark
for m = marks
% Only count the student if they passed
if m >= 50
% Add to the total the current mark
total = total + m;
end
end
% Print total to screen
disp(total);
ENGG1801 Engineering Computing
24
•We can combine many things and print them all on one line, using an array:
% Display “height” on the screen
disp(‘height’);
% Display the value of variable ‘height’
disp(height);
% Display many things on one line on screen
disp([‘Bridge height: ’, num2str(height), ‘ metres’]);
% Display height to 3 significant figures
disp([‘Bridge height: ’, num2str(height, 3), ‘ metres’]);
25
ENGG1801 Engineering Computing
26
•We can display text on separate lines % Display 2 strings on separate lines disp(‘abc’);
disp(‘def’);
% This does the same thing
% as above, using the
% fprintf function and ‘\n’
% (the new line character)
fprintf(‘abc\ndef\n’);
ENGG1801 Engineering Computing
27
•We needed the \n at the end, otherwise the >>prompt will appear on the same line as our text:
% This is the same as the
% previous slide, but
% without the ‘\n’ at the end
fprintf(‘abc\ndef’);
ENGG1801 Engineering Computing
•Suppose we want our output like this: pi = 3.1416
e = 2.7183
•We can use the fprintf function to output text data more neatly
–The first parameter is a string that contains
parts beginning with %
–These parts are replaced (in order) by the
values of variables of the other parameters
28
ENGG1801 Engineering Computing
29
ENGG1801 Engineering Computing Format Meaning
%d Integer
%e Scientific notation with number of significant figures
%f Fixed point with number of decimal places
%g %e or %f , whichever uses least space
%s Display a string (series of characters)unchanged
•The string containing parts in the form
%w.df
–w is the min width (left padded with spaces)
–d is number of decimal places (using %f)
(default is 6)
–d is number of significant figures
(using %e or %g)
–f can be replaced with any letter from the
table on the previous slide
30
ENGG1801 Engineering Computing
•We want our output like this:
pi = 3.1416
•We use the fprintf function like this: % %s-Print a string
% %5s-Print at least 5 characters, spaces on left if needed % %–5s-Same as above, but spaces on right
% %10.4f-Print value of decimal number to 4 decimal places, %at least 10 characters, spaces on left if needed
% pi is a variable in Matlab that automatically has the value of pi fprintf(‘%–5s = %10.4f\n’, ‘pi’, pi);
31
ENGG1801 Engineering Computing
•Suppose we want our output in scientific notation, but without padding, like this: Avegadros number = 6.022e+023
•We use the fprintf function like this:
% %.3e-Print in scientific notation, to 4
%significant figures, but without
%padding (hence no number before
%decimal)
fprintf(‘Avegadros number = %.3e\n’, 6.022e23);
32
ENGG1801 Engineering Computing
33
•Using the logic on the previous slides,you should understand these examples:
ENGG1801 Engineering Computing
•Suppose we want our output like this: data( 1) = 8.507
data( 2) = 12.606
data( 3) = 9.296
data( 4) = 6.967
data( 5) = 13.828
data( 6) = 8.154
data( 7) = 8.790
data( 8) = 9.889
data( 9) = 10.005
data(10) = 8.654
34
ENGG1801 Engineering Computing
•For this example (previous slide):
–The index must take up 2 characters, left
padded with spaces if necessary
–The value is fixed (decimal) format
•Left padded width of 10
•3 decimal places
35
ENGG1801 Engineering Computing
% Assuming that the ‘data’ array has already
% been created, go through each element
for i = 1:length(data)
% %2d is replaced by i
% 2 means padded width of 2
% d means integer
% %10.3f is replaced by data(i)
% 10 means padded width of 10
% .3 means 3 decimal places
% f means fixed point with number of decimals fprintf(‘data(%2d) = %10.3f\n’, i, data(i));
end
36
ENGG1801 Engineering Computing
•fprintf can also be used to output to files % Prepare to write to a file. We use the fopen
% function, giving it the filename to write and ‘w’
% to indicate that we are writing. It returns a file
% descriptor which function fprintf needs.
file = fopen(‘results.txt’, ‘w’);
% Write some lines of text to the file
fprintf(file, ‘%–5s = %10.4f\n’, ‘pi’, pi);
fprintf(file, ‘%–5s = %10.4f\n’, ‘e’, exp(1));
% Close the file so that it saves properly
fclose(file);
37
ENGG1801 Engineering Computing
•After running the previous code, the file results.txt will look like this:
pi = 3.1416
e = 2.7183
38
ENGG1801 Engineering Computing
•File I/O (Input / Output)
–Reading files into matrices with dlmread, etc.
–Writing matrices to file with csvwrite, etc.
–Writing formatted text to file with fprintf
We can now read from and
write to files of different formats
39
ENGG1801 Engineering Computing
•Text I/O
–Reading text from the user (keyboard) with input
–Writing many things on one line with disp and arrays –Writing formatted text to screen with fprintf
We can now read user input
while the program runs,
and also format data to screen
40
ENGG1801 Engineering Computing。