lecture10_matlab_io
lecture10_matlab_io
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
West
pie, hist
3D plotting
1. Define x-vector
2. Define y-vector
3. Define z-vector
4. plot3(x,y,z)
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.
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:
xlabel
ylabel
title
grid on
To add text at the position xpos, ypos to the current axes use:
>> text(xpos, ypos, ‘some_string’);
To override use:
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.
Screen
Figure1
Axes1 (xlabel, ylabel, title, tick marks, tick labels)
Graph1 (linestyle, legendlabel)
Graph2
…
Axes2
Graph1
…
Figure2
Axes1
Graph1
Graph2
Axes2
Graph1
…
To highlight a figure that is already displayed (if it doesn’t already exist, it will be created):
>> figure(2)
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
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)
hold on
plot(x,y,'‐.')
title
legend
hold off
close all
figure
axes(‘position’, [xorigin
yorigin xwidth yheight]);
– for finer control than
subplot
• Load data from an ASCII file into an array (must look like an array)
>> a=load('numeric_array.txt')
a=
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.
% saves all workspace variables to the file foobar.mat (.mat extension is optional)
% saves all workspace variables that begin with the letters 'sta' (* is a wildcard)
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).
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.
You are responsible for opening and closing the file though.
The latter are only used for writing data out to file.
Script:
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
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
raw – a cell array contain any columns xlsread could not interpret
% 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
% 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
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
% define a vectors in a cell array which have row numbers for each plot
i{1} = 7:4:23;
...
i{5} = 82:4:102;
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)