0% found this document useful (0 votes)
9 views

lecture10_matlab_io

Uploaded by

Mab Abdul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

lecture10_matlab_io

Uploaded by

Mab Abdul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Beyond the Mouse

MATLAB Input & Output


(Getting data into MATLAB and plotting it)
The goal

Spend less time doing stuff computers are good at, and more time doing science
(i.e. stuff you can publish).
OR
A program that generates all the figures you need for a paper (or a chapter of
your thesis). New dataset -> rerun program -> new paper.

EFFICIENCY / PRODUCTIVITY
Today’s schedule

1. Plotting data with MATLAB


2. Annotating plots (xlabel, ylabel, legend, …)
3. Multiple plots on a figure
4. Saving figures
5. Getting data into MATLAB
6. Miscellaneous
7. Examples
8. Exercises
1. Plotting data with MATLAB
plot
2D plotting

1. Define x-vector >> x = 1:20;


2. Define y-vector >> y = x^2;

3. plot(x,y) >> plot(x, y)

plot just gives a normal x-y graph with linear axes.


North

West

There are other 2D plotting commands, e.g: South

semilogy, semilogx, loglog


stem, stairs, bar East

pie, hist
3D plotting

1. Define x-vector
2. Define y-vector
3. Define z-vector
4. plot3(x,y,z)

There are other 3D plotting


commands, e.g:
surf, mesh, contour
pie3, bar3, hist3
3D plotting – 3rd dimension as color

An array can be plotted, using different colours to represent different values.

Example:
>> a = rand(100, 100); % 100 x 100 array of random numbers from 0 to 1
>> imagesc(a);
>> colorbar;
Spectrograms, on the AVO
internal webpage, are
created in this way, except
the array is generated
using the specgram()
command.

(There are 15 different


axes on this plot).
Plotting maps: the Mapping Toolbox

>> help map


>> mapdemos

Can write KML (GoogleEarth):


>> help kmlwrite

Alternative to GMT
2. Annotating plots
Changing the line style: plot(x,y,s)
By default, plot(x,y) uses a blue line to connect data points
>> help plot

Various line types, plot symbols and colors may be obtained with
PLOT(X,Y,S) where S is a character string made from one element
from any or all the following 3 columns:

b blue . point - solid


g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
w white v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
plot(x,y,s)

plot(x,y,'rx') plot(x,y,'bo') plot(x, y, 'mv‐')

red crosses black circles magenta triangles + line


Labelling axes

xlabel
ylabel
title
grid on

Superscripts: ‘time^2’ => time2


Subscripts: ‘SO_2’ => SO2
Greek characters: \alpha => α
Adding text

To add text at the position xpos, ypos to the current axes use:
>> text(xpos, ypos, ‘some_string’);

Remember you can use sprintf.


>> text(2.3, 5.1, sprintf(‘station %s’,station{stationNum}) );
Changing the data range shown

Default: show all the data.

To override use:

>> set(gca, ‘XLim’, [xmin xmax]); % x-axis only


>> set(gca, ‘YLim’, [ymin ymax]); % y-axis only
>> set(gca, ‘XLim’, [xmin xmax], ‘YLim’, [ymin ymax]); % both axes
Changing the tick positions/labels

set(gca, 'XTick', 1:3:22) set(gca, 'XTickLabel', {50, 'Fred', 'March', 'Tuesday', 75.5, 999, 'foobar'})
Plotting against date/time: datenum & datetick
datenum() returns the day number (and fractional day number) in the calendar starting 1st January
in the year 0 AD.

Excel dates and times are similar except Excel uses the origin 1st January 1900. But you normally ask
Excel to format those cells with a particular date/time format, so you don’t see the raw numbers. In
MATLAB, datenum gives those raw numbers.

To convert from Excel day‐numbers to MATLAB datenum format:


mtime = etime + datenum(1900, 1, 1);
Call it like:
datenum(YYYY, MM, DD)
datenum(YYYY, MM, DD, hh, mi, ss)
datenum(‘2009/04/29 18:27:00’)

Remember to use vectorisation:


redoubtEventTimes = {‘2009/03/22 22:38’; ‘2009/03/23 04:11’; ‘2009/03/23 06:23’}
dnum = datenum(redoubtEventTimes); % result is a 3 x 1 vector of datenums.
datetick(‘x’); % can give unexpected results, ask for help.
datestr

I often use dates in plot labels, or in file paths/names.

datestr(array, dateform) is used to generate a human‐readable string from an array of


dates/times in datenum format.

>> lectureTime = datenum(2009, 4, 29, 12, 30, 0)


733890.5208
>> datestr(lectureTime, 30)
20090427T123000
>> datestr(lectureTime, 31)
2009‐04‐29 12:30:00
>> datestr(lectureTime, ‘mm/dd/yyyy’)
04/29/2009
>> xlabel( sprintf(‘This plot was generated at %s’, datestr(now, 31) ) );

An aside – making dates work for you:


YYYYMMDD, not MMYYDD (U.S.) or DDMMYY (Europe).
3. Multiple plots on a figure
MATLAB Graphics Object Hierarchy

Screen
Figure1
Axes1 (xlabel, ylabel, title, tick marks, tick labels)
Graph1 (linestyle, legendlabel)
Graph2

Axes2
Graph1

Figure2
Axes1
Graph1
Graph2
Axes2
Graph1

figure axes plot


figure
To create a new figure with no axes:
>> figure;

To highlight a figure that is already displayed (if it doesn’t already exist, it will be created):
>> figure(2)

To get all the properties associated with a figure:


>> get(figure(2))

To get a particular property associated with a figure:


>> get(figure(1), ‘Position’)
[420 528 560 420]

To modify a particular property associated with a figure:


>> set(figure(1), ‘Position’, [100 100 560 420])

This particular example will just move where figure(1) is plotted on the screen.

To get a ‘handle’ for the current active figure window use gcf.
>> get(gcf, ‘Position’)
Will return the screen position of the current active figure window.
axes

New figures are created without a set of axes.

To get a ‘handle’ for the current active set of axes use gca (get current axes).
Example: get a list of all properties associated with current axes
>> get(gca)

>> get(gca, ‘position’)


This will return the screen position of the current active figure window, which by default is:
[0.13 0.11 0.775 0.815]
Format here is [xorigin yorigin xwidth yheight] in fractions of the figure window width.

To modify the position of the current axes within a figure:


>> set(gca, ‘position’, [0.2 0.3 0.6 0.4])
The axes would start 20% of the way across the screen, 30% of the way up,
and be 60% the screen width, and 40% the screen height.

An alternative syntax is just to call the axes command:

>> axes(‘position’, [0.2 0.3 0.6 0.4]);


Either will create a figure if none already exists. Or modify the current set of axes on the
current figure.
Multiple plots on a figure 1: hold on
hold on “holds on” to graphs already
in the current axes.
Normally they would be erased

hold on
plot(x,y,'‐.')
title
legend
hold off

If your graphs have very


different scales, and you
have just two, try plotyy
Multiple plots on a figure 2: subplot

close all
figure

subplot(M, N, plotnum) ‐ an M x N array of plot axes


Multiple plots on a figure 3: axes(‘position’, [ …])

axes(‘position’, [xorigin
yorigin xwidth yheight]);
– for finer control than
subplot

set(gca, 'XTickLabel', {})


‐ remove x tick labels
Multiple plots on a figure 4: long form of plot command
plot(x1, y1, x2, y2, …, xn, yn)
% a way of plotting multiple graphs
without using hold on

plot(x1, y1, s1, x2, y2, s2, …, xn, yn, sn)


% as above, but override the default line
styles.

You can then use legend to create a key


for the different graphs in your figure.
4. Savings figures to image files
Writing an image file - print
print ‐f1 ‐dpng myplotfilename.png ‐ script form
print('‐f1', '‐dpng', '‐r200', 'myplotfilename.png') ‐ functional form
‐r200 means print with resolution 200 dots per inch (use lower number for small plot)
‐f2 means print figure 2
Devices include:
ps, psc, ps2, psc2 ‐ Postscript (c = colour, 2 = level 2)
eps, epsc, eps2, eps2 ‐ Encapsulated Postscript (c = colour, 2 =
level 2)
ill ‐ Adobe Illustrator format
jpeg90 ‐ JPEG with quality 90 (can be 01 to 99)
tiff ‐ TIFF
png ‐ PNG
Can also capture a figure window with:
>> print –dmeta
on a Windows system, and paste it into
your document. It does the same thing
as ALT‐PRT SC.
Writing an image file - print
Example:
You have (numberOfPlots) figures and you want to save all of them as level‐2 color
encapsulated postscript files with names like myplot1.eps, myplot2.eps:

for plotNum = 1 : numberOfPlots


print('‐depsc2', sprintf('‐f%d',plotNum), '‐r70',
sprintf('myplot%d.eps',plotNum) );
end

For plotNum = 2, the print line would evaluate to:


print('‐depsc2', '‐f2', '‐r70', 'myplot2.eps')
5. Reading (and writing) data
from files
load

• Load data from an ASCII file into an array (must look like an array)

>> a=load('numeric_array.txt')

a=

0.0799 0.8979 ‐1.0149


‐0.9485 ‐0.1319 ‐0.4711
0.4115 ‐0.1472 0.1370
0.6770 1.0078 ‐0.2919
0.8577 ‐2.1237 0.3018
‐0.6912 ‐0.5046 0.3999
0.4494 ‐1.2706 ‐0.9300
0.1006 ‐0.3826 ‐0.1768
0.8261 0.6487 ‐2.1321
0.5362 0.8257 1.1454

??? Error using ==> load


Number of columns on line 5 of ASCII file numeric_array.txt
must be the same as previous lines.

• Load variables from a MATLAB binary file (*.mat)


load() wont work at all with alphabetic characters

s=load('string_array.txt')
??? Error using ==> load
Unknown text on line number 1 of ASCII file string_array.txt
"free".
MATLAB binary files

Only MATLAB can read/write them. Useful for storing (workspace) variables, so you
can reload them later. Use save and load. Support numeric arrays, strings, cell arrays
and structs.

>> save foobar.mat

% saves all workspace variables to the file foobar.mat (.mat extension is optional)

>> save foobar.mat x y

% saves only the workspace variables x and y to the file foobar2.mat

>> save foobar.mat sta*

% saves all workspace variables that begin with the letters 'sta' (* is a wildcard)

>> load foobar.mat % loads the file foobar.mat

>> load foobar x % loads only the variable x from foobar.mat


importdata

load wont work with strings. A more versatile


function is:

A = importdata('filename.txt', 'delimiter') >> a=importdata('numeric_array3.txt')

a=
It works without any difficulty for any of the ASCII
files we've seen so far: 1 2 3 4
5 6 7 NaN
8 9 10 11

>> s=importdata('string_array.txt')

s=

'fred'
'bill'
'norm'
'mike'
'dick'
'jane'
'jill' Loads string_array.txt into a
'bing' cell array
'brad'
'dave'

>>
More ambitious – each row is a string followed of length 1 to 11
followed by 0 to 4 numbers (reals and integers).

It has created a struct,


s2.data holds the
numeric array,
s2.textdata holds the
string data in a cell array

Non‐existent values
replaced with NaN in
numeric array
But importdata finally fails to work
as desired when we are reading in a
simple file made of 3 strings per row.

It loads each row into a single


element of a cell array.
textscan

cols = textscan(fid, format) works. Each column goes into a


separate element of a cell array.

You are responsible for opening and closing the file though.

fid = fopen(filename, mode)

Is used to open a file.


Mode is:
‘r’ read (default)
‘w’ write (overwrite if file already exists)
‘a’ append (append to existing file if it already
exists)

The latter are only used for writing data out to file.

fclose(fid) is used to close the file, after you’ve read (or


written) it.
Example to plot birthdays
against name using:
fopen/textscan/fclose
struct
datenum
plot(y)
datetick
change XTickLabel

Script:

% read the file


fid = fopen('mixed_array3.txt');
A = textscan(fid, '%s %d %s %s');
fclose(fid);

% convert data into a struct


person.name = A{1};
person.age = A{2};
person.bday = datenum(A{3}); % convert to a datenum
person.phoneNum = A{4};

% plot the data


figure;
plot(person.bday);
datetick('y'); % let Matlab figure out how to label the y‐axis
set(gca, 'XTickLabel', person.name); % change the XtickLabels from1:7 to names
Read a line - fgetl

Line can be any length, any format.

Useful when each line has fields which appear in fixed positions.
I often use it when each line has fields which appear in fixed positions.
Read a data type - fscanf
Writing to a file - fprintf

fout = fopen(filename, 'w') % write to new file filename (replacing file it if already
exists)
for (r=1:numRows ) % loop over all rows

fprintf(fout, '%s\t%12.7f\n', datestr(dnum(r),31), data(r));

end
fclose(fout)

\t = <tab>
\n = <return>
datestr(dnum(r), 31) = print dnum(r) as a datestr using dateform 31
%12.7f= print this real variable as 12 characters with 7 after the decimal
point

Output file might be like: Related functions:


dlmwrite – for delimited fields
20090423T180000 1234.1234567
20090423T180100 1357.1357911 (csvwrite for comma delimited fields)
20090423T180200 1470.1470369
Reading
Read Excelfile
an Excel files
- xlsread

[numeric, txt, raw] = xlsread('myfile.xls'); % will attempt to read all


sheets

[numeric, txt, raw] = xlsread('myfile.xls', 'sheet1'); % read sheet1 only

numeric – a matrix that contains all the numeric columns

txt – a cell array contain all text columns

raw – a cell array contain any columns xlsread could not interpret

Related functions are csvread and dlmread


Writing an Excel file - xlswrite

Writing Excel files

xlswrite('myfile.xls', myarray, 'sheet2');

myarray ‐ a numeric array or a cell array

Related functions are csvwrite, dlmwrite


6. Miscellaneous I/O
Graphical input

% A simple menu
choice = 0;
while (choice ~= 4)
choice = menu('Main menu', 'load file', 'plot data', 'filter data',
'exit')
switch choice
case 1, loadFile();
case 2, plotData();
case 3, filterData();
end
end

% Get filename dialog


[filename, dirname] = uigetfile();

% Save filename dialog


[filename, dirname] = uiputfile();

% Getting input coordinates from the mouse


[x, y] = ginput(2); % input 2 data points

 useful for picking P and S arrival times


 or start and end of tremor or swarm episodes
 or start and end of episodes of increased degassing

% Designing GUIs
guide;
7. Summary

Plotting commands:
- plot, semilogx, semilogy, loglog, bar, barh, stem, stairs, hist, pie

- plot3, bar3, pie3, hist3, contour, surf, mesh, quiver, (mapping toolbox)

- image, imagesc

- datetick (datenum, datestr), subplot, hold on, axes

Graphical files:
‐ imread, print
Not covered: reading
MAT(LAB binary) files:
and writing generic
-load, save
binary files with:
fopen, fread, fwrite,
Numerical ASCII files: fseek, fclose
- load, importdata, save

Text files:
- importdata, textscan, fgetl, fscanf, fprintf (fopen/fclose)

Excel files:
‐ xlsread, xlswrite
8. Examples
Flyspec data, courtesy of Taryn Lopez

“The FLYSPEC File


Kary72208_P20.xls, contains:
scan number
year
date
month
hour
min
second
time (HHMMSS)
lat (degree dec min)
(N)
long (deg dec min)
(E)
Don't know the next 3 columns...
Column 17 is SO2 column density
Column 18 is SO2 emission rate

plot… SO2 emission rate vs time.”


Grasshopper diet data, courtesy of Ellen Trainor
apply a conversion factor
to all measurements

plot the first six rows in


bold as 6 lines on a plot

compute the area under


each line

do the same for the next 6


bold rows

then the next 5

then the next 5

then the next 7

then the next 4


function grasshopperDiets()

% define conversion factor


conversionFactor = 1.98 * 12 / (12 + 2 * 16);

% load the data


[a, t] = xlsread('grasshopperDiets.xls');
day = a(3, :); % day is in row 3

% apply conversion factor


a[4:109, :] = a[4:109, :] * conversionFactor;

% set colours to match Excel


color = 'bmycrgk';

% define a vectors in a cell array which have row numbers for each plot
i{1} = 7:4:23;
...
i{5} = 82:4:102;

% loop over each set of rows defined in an element of i{ }


for count = 1:length(i)

% plot these rows & compute area under graph


[area{count}, legendStr] = areas(day, a, i{count}, color, t);

% plot a bar graph of the area


plotarea(area{count}, color, legendStr)

end
Exercises (optional)
Write scripts (or functions) to do the following:

Exercise 1:
• (Download the image file http://www.avo.alaska.edu/images/logos/logo_avo_transparent_new.jpg).
• Load the image into MATLAB (into an array A) with imread
• Plot it with imagesc
• Find the size of the array
• Find the minimum and maximum values
• Add a colorbar
• Add a title, xlabel, ylabel
• Move the figure on the screen with set(gcf, ‘Position’, …)
• Move the axes with set(gca, ‘position’, …)

Exercise 2:
• Store rows 5, 10 and 20 of the array A in new vectors
• In a new figure, plot (in 2D) each of those 3 vectors in a different subplot
• In a new figure, plot (in 2D) each of those 3 vectors on same axes using hold on
• set the range of data shown (zoom in)
• set tick position
• Add xlabel, ylabel, title and legend.
• print to an EPS file

Exercise 3:
• Load an Excel worksheet containing data (xlsread)
• plot some of the data in MATLAB.
• print to a PNG file.
• View the PNG file in your web browser.
• Modify the data in MATLAB.
• Write to new data back to a worksheet in Excel (xlswrite)

Send your scripts to [email protected] if you want feedback.

You might also like