MEEN 2240
PROGRAMMING FOR
MECHANICAL ENGINEERS
Instructor: Dr. Yunwei Xu
Dept of Mechanical Engineering
University of North Texas
Chapter 5
File Input and Output (Load and Save)
Copyright © 2020 Yunwei Xu, PhD 2
File: load and save
There are some simple file commands for reading and saving a matrix to a file into
a matrix: save
and load
• load—this function will load and create a matrix variable named filename
• Load: load loaddata.txt
• Data will be stored in a matrix named loaddata
• save—function will save matrix data into a file
• To write the contents of a matrix variable to a file Save: save
filename.txt variable –ascii
• To append to an existing file: save filename.txt variable –
ascii -append
Copyright © 2020 Yunwei Xu, PhD 3
Load and Save Example
Example 1:
% Create the data for the temperatures and months
temperatures = [48.5 57.3 69.2 79.3 86.9 87.9 83.1 75.5
67.7 59.3 51.7 46.0];
months = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
p1(:,1) = temperatures;
p1(:,2) = months;
Save data in matrix form p1
save plotdata.txt p1 -ascii
load plotdata.txt
% Plot the temperatures on a bar chart
figure
temp = plotdata(:,1);
month = plotdata(:,2); Read the saved
barh(temp) data in plotdata
% Set the axis limits file
axis([0 90 0 13])
% Add a title
title(' Dallas Monthly Average Temperature')
xlabel('Temperature F')
ylabel('Month')
create horizontal bar
change the length of axes
Copyright © 2020 Yunwei Xu, PhD 4
Practices
Example 2-1:
A car moves for a short time with its position, velocity and acceleration are defined as
shown below.
s = t4 + t3 + t
v = 4t 3 + 3t 2 + 1
Determine the values for position, velocity for times starting at 0 and ending at 2 sec. Use 0.2
sec increments. Put the time, position, and velocity data into a table called car_data. Save this
table to a file called ‘car.txt’. Verify the data is in the file.
clear all
clc
t=0:0.2:2;
position=t.^4+t.^3+t;
velocity=4*t.^3+3*t.^2+1;
car_data(:,1)=t';
car_data(:,2)=position';
car_data(:,3)=velocity';
save car.txt car_data -ascii
Copyright © 2020 Yunwei Xu, PhD 5
Practices
Example 2-2:
Now, please add data to the car.txt file. Now calculate position, velocity for time values of 2
to 5 sec. Use 1 sec increments. Append this new data to the data in car.txt.
clear all
clc
t=2:1:5;
position=t.^4+t.^3+t;
velocity=4*t.^3+3*t.^2+1;
car_data(:,1)=t';
car_data(:,2)=position';
car_data(:,3)=velocity';
save car.txt car_data -ascii -append
Copyright © 2020 Yunwei Xu, PhD 6