Whenever I write [Octave] it means the stuff also works in Octave
General
Functions
I/O
Debug
Dates and times
Strings
Plot
Surface fitting
General
Entering long statements
use ‘…’
all_data = textscan(fid, ['%n %n.%n.%n-%n.%n %n %s %n %s %d %s %d' ...
%s %d %s']);
Output format [Octave]
format
Most used options:
short
long
rat:
ratio
Variable type
whos myVar
Difference between && and &
&& is a short-circuit version of the & logical operator meaning when entering
a && b
Matlab first evaluates a and if it is wrong, terminates immediately without evaluating b
Example:
if ( (x > 0) && (1/x <3) ) % 1/x will never be evaluated with x = 0
Functions
Making new functions visible
If you’re creating a new function with an editor that is not the Matlab editor, Matlab doesn’t detect it automatically. You solve this problem by typing
clear functions
Of course the function file must be in your path, otherwise you can add it from the File menu
Syntax
function y = average(x)
% AVERAGE Mean of vector elements.
% only first comment line is printed when you type "lookfor average"
% the other lines print when you type "help average"
y = sum(x)/length(x); % Actual computation
function [Xout,Yout] = myFunc(x)
Number of arguments
nargin: number of input arguments
nargout: number of output arguments
Variable number of input arguments
function testvar(x1, x2, varargin)
Varargin is a cell array. In the function body, access its cell values like this:
varargin{i}(k)
Variable number of output arguments
function [varargout] = testvar2(arrayin)
Varargout is a cell array. Assign the cell values like this:
varargout{i} = arrayin(k,:);
Anonymous functions
Does not require an M-file (perfect for defining functions in the command line)
f = @(arglist) expression
example:
sqr = @(x) x.^2;
I/O
Open a formatted text file
fid = fopen('file.dat','w')
w
: write
r
: read
a
: append
returns -1 if error
If the file is a text file and you want to write to it, consider using ‘t’ as an attribute if you want Windows line break
example:
fid = fopen('file.txt', 'wt')
Close file
fclose(fid)
fclose('all') % closes all open files
Filename
[pathstr, name, ext, versn] = fileparts(filein);
fileout = fullfile(pathstr, [name, '.out']);
Write to formatted text file (line by line)
fprintf(fid,'%2.4f\n',x)
fid: 1 = stdout; 2 = stderr
omitting fid writes on the screen
d: integer
f: fixed point notation
e: exponential notation
g: same as f or e but insignificant zeros do not print
s: string of characters
c: character
Remember \n for line break
fprintf tips
Printing strings and numbers together: it looks like you have to separate the printing of strings and numbers into distinct fprintf statements. Example:
fprintf(fid, '%s', 'test ');
fprintf(fid, '%d %d\n', 10, 20); %printed on the same line as 'test
‘
Write (numeric) matrices to text file
A = [1 2 3 4 ; 5 6 7 8];
dlmwrite('my_data.out', A, ';')
‘;’ is the delimiter in my_data.out
” means no delimiter
Note: not necessary to open the file first
Note: use the following notation if you want Windows line break:
dlmwrite('my_data.out', A, 'delimiter', ';', 'newline', 'pc')
To decide the number precision use the ‘precision’ attribute
'precision', '%10.5f
‘
Read ASCII delimited numeric data file
data = dlmread('myfile.dat');
col1 = data(:,1);
Read from file containing numbers and strings
textscan
example:
Text file scan1.dat contains data in the following form:
Sally Level1 12.34 45 1.23e10 inf NaN Yes
Joe Level2 23.54 60 9e19 -inf 0.001 No
Bill Level3 34.90 12 2e5 10 100 No
Read each column into a variable:
fid = fopen('scan1.dat');
C = textscan(fid, '%s %s %f32 %d8 %u %f %f %s');
fclose(fid);
Specifiers:
%s : string
%n : double
%d : int
Note that textscan returns a cell array. Therefore C{1} is the cell array containing the surnames ‘Sally’, ‘Joe’ and ‘Bill’. C{1}(1) is the cell containing the string ‘Sally’. To convert this cell to a string (i.e. a character array), use the char function:
sallyString = char(C{1}(1));
The conversion is necessary e.g. if you want to write out the string using fprintf
Read file containing numbers and NaN
example:
nc = 6; % number of columns of data in the input file
fmt = repmat('%n', 1, nc);
clear m;
[m{1:nc}] = textread(filein, fmt);
m = cat(2,m{:});
Delimiters (textscan and textread)
Default delimiter:
' \b\t
‘
To use a different delimiter:
C = textscan(fid, '%s %n', 'delimiter', '\t');
If a nondefault delimiter is specified, repeated delimiter characters are treated as separate delimiters. When using the default delimiter, repeated white-space characters are treated as a single delimiter.
Skipping fields (textscan and textread)
Use asterisk: %*s instead of %s
Particularly handy when using textread where you can write the data directly into a list of variables
Error message
error('ERROR: wrong format');
Debug
Debug a function that requires arguments
Open the function file in the editor
edit function.m
Run the function from the command line
function(x,y)
For private functions:
edit private/privFunc.m
Commands
disp(val): display values while debugging (or simply val)
return : continue execution
dbstep : execute current line
dbquit : exit debugging
Measure time use
tic, toc: measure the time elapsed between invoking
Dates and times
Date formats
Date string: 24-Apr-2006
Serial date number: 732791
Date vector: 2006 04 24 0 0 0
Conversion functions
datenum: convert to a serial date. In Octave 1 Jan 0000 is defined as day 1.
datestr: convert to string representation of the date
datevec: convert to a date vector
Example: the 265th day of year 2007 is
datestr(datenum(2007,01,01) + 264)
Strings
Concatenate strings
newString = [string1, string2, string3];
Convert an integer to a string
newString = int2str(n);
Plot
Plot with dates
Example:
plot(dates, y);
datetick('x', 19);
Note1: dates must be a vector of serial dates (obtained with datenum)
Note2: 19 is one of a series of different formats that datetick can print the date into.
Note3: you might want to add ‘keepticks’ as a third input argument in order to get a good tick repartition.
Subplots
You can plot several plots in the same window with the subplot command.
Example – drawing two plots next to each other:
subplot(1,2,1);
plot(x1,y1);
subplot(1,2,2);
plot(x2,y2);
The two first figures indicate how the window is split, here 1 row and 2 columns while the third figure is the subwindow index.
Double axis graphs
In order to plot y1=f(x1) and y2=g(x2) with two Y-axes, copy the following lines:
line(x1,y1,'Color','r');
ax1 = gca;
set(ax1,'XColor','r','YColor','r')
ax2 = axes( 'Position',get(ax1,'Position'),. . .
'XAxisLocation','top',. . .
'YAxisLocation','right',. . .
'Color','none',. . .
'XColor','k','YColor','k');
line(x2,y2,'Color','k','Parent',ax2);
Plot several data sets
Each time you call the plot
command, it clears the plot window. If you want to keep the previous plot, you need to write
hold all
before the first plot
command and
Remember to write
hold off
after the last plot
command. That way, the plot window will behave “normally” on the next plot
call.
Grid
Examples:
set(gca, 'XGrid', 'on')
set(gca, 'XMinorGrid', 'off')
Write text in the plot window
The easiest way is to use the text
command:
text(xpos, ypos, str)
Check also out the annotations
command
Fix X and Y limits
xlim([xmin xmax])
ylim([ymin ymax])
Surface fitting
You have a non-uniform collection of measured points (from total station, differential gps, etc.) and you want to plot an interpolated surface.
Suppose your points are stored as X, Y, Z.
First you build a uniform grid based on the extremities of the measured area:
[Xm, Ym] = meshgrid (Xmin:s:Xmax, Ymin:s:Ymax);
where s is the grid size
Then you interpolate the surface at all the grid points:
Zm = griddata (X, Y, Z, Xm, Ym);
Eventually you may plot the surface:
surf(Zi)