To set the path for directories which Matlab should see:
path(path, 'c:\mydocu~1\...')
Write this in file "startup.m" in the directory $Matlab\toolbox\local\
Write m-file to define functions or executable commands, which can be called by writing the name of the file.
Continuation
To break a line use ... (three dots).
Save
To save a variable:
save variable
Options:
-ascii Use 8-digit number format
-ascii -double Use 16-digit number format
-ascii -double -tabs Delimit array elements with tabs.
-v4 Create a file for Matlab4
-append Append data to an existing MAT-file
Format
format short
1.3333
format short e
1.3333e+000
format long
1.33333333333333
format long e
1.333333333333333e+000
Plot
To plot a function use:
plot(x,y, '- (or -. or * or +)')
where x and y are arrays of the same dimension.
To change the size of the marker use 'MarkerSize', # (12, for example)
Options: axis([x_initial x_final y_initial y_final])
axis auto re-enable automatic limits selection
title('.....')
x,y,zlabel('....')
grid on % to have a grid
grid off % to delete the grid
We can identify multiple plots by using legend. Ex:
plot(x1,y1,x2,y2)
legend('plot1','plot2')
COLORDEF Set color defaults.
COLORDEF WHITE or COLORDEF BLACK changes the color defaults on the root so that subsequent figures produce plots with a white or
black axes background color. The figure background color is changed to be a shade of gray and many other defaults are changed so that there will
be adequate contrast for most plots.
Text
To put text on the graph:
text(x,y,'...','Fontsize',...,'FontName','Times')
Fontsize defines the dimension of the fonts, FontName the fonts
Subplot
To display multiple plots in the same window:
subplot(m,n,p)
where the window is partitioned in a m x n matrix, and p selects the position of the current subplot
Windows
To open a new graphic window, type:
figure
figure(n)
activates the window # n
Print
To print a figure in a eps file, with a TIFF preview:
print -depsc2 -tiff figure.eps
Differential Equation Solvers
To solve a differential equation numerically, there are different methods:
ode15s, ode23, ode45
Example:
Define a function in a separate m-file:
function dy = ex1(t,y)
dy = zeros(4,1);
dy(1) = y(3); %y(1)=x
dy(2) = y(4); %y(2)=y
dy(3) = -y(3); %y(3)=v_x
dy(4) = -y(4)-9.81; %y(4)=v_y
The command to compute the solution is:
[T, Y] = ode...('function', [T_initial T_final], [initial conditions], options)
To set options, write before the previous line:
options = odeset('RelTol', ...., 'AbsTol', [ as many as variables in the ODE]);
The plot can be done by:
plot(Y(:,1), Y(:,2), '-' )
Event Detection
To stop integration at a given event:
In the main file type:
options = odeset(...'Events','on'); % This checks for the event in the function
[T,Y, te,ye,ie]= solver('function', [tspan],[Incon], options);
In the function:
function varargout = myfunction(t,y,flag) % varargout allows any number of output arguments from a function.
switch flag % open switch
case '' % no flag
dy=zeros(n,1);
dy(1)=...;
...
dy(n)=...;
[varargout{1}]=dy;
case 'events'
[varargout{1:3}]=events(t,y);
end
function [value, isterminal,direction]= events(t,y)
value=... % variable to be checked
isterminal =... % a vector of 1 or 0 of the same dimension of value. 1 stop the integration.
direction=... % a vector of the same dimension of value. Specify the direction of zero crossing:
% -1 for negative value, 1 for positive and 0 for no preference.
Animation
See also Prata pp. 189.
To create an animation:
h=plot(x1,y1, 'marker','o', 'markersize', n,'erase','xor'); % This set the graphic object, define a marker type ('o'), and
% size (n), and the appearance of the object when the graphic
% screen is redrawn (xor erase previous version of the object,
% none leave previous versions on the screen.
x1=... % This can also go before.
y1=...
axis ([...]); axis square % To get same scale on the plot and a defined range.
for k=2:length(T) % Start for cycle, with arbitrary number of iterations
set(h1, 'xdata', x1, 'ydata', y1); % Draw the point at the new position
drawnow % Flushes the graphics output to the screen without waiting for
% the control to return to MATLAB.
end % end for cycle
AVI file
To obtain a movie:
for k=1:n
plot(whatever)
M(k) = getframe(gcf); % That store the plots in a matrix, (gcf) is to get the whole screen, axis and label
included
end
movie(M) % That project the movie
To get an avi file:
movie2avi(M,'filename', 'fps',#) % fps =frame per second (usually 16)
To see an avi file:
xanim filename.avi &
Statistics
To obtain the dimension of an array:
[n,p] = size(file)
To create a vector of integers:
t=1:n;
A list of functions which provide column-oriented data analysis can be found at:
file:/mnt/cdrom/help/techdoc/using_ml/using_ml.html
Outliers: how to eliminate them.
You can remove outliers or misplaced data points from a data set in much the same manner as NaNs. For the vehicle traffic count
data, the mean and standard deviations of each column of the data are (count is the data file):
mu = mean(count);
sigma = std(count);
The number of rows with outliers greater than three standard deviations is obtained with:
[n,p] = size(count)
outliers = abs(count - mu(ones(n, 1),:)) > 3*sigma(ones(n, 1),:);
nout = sum(outliers)
nout =
1 0 0
There is one outlier in the first column. Remove this entire observation with
count(any(outliers'),:) = [ ];
Polyfit
POLYFIT Fit polynomial to data.
POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) of degree N that fits the data, P(X(I))~=Y(I), in a least-squares sense.
[P,S] = POLYFIT(X,Y,N) returns the polynomial coefficients P and a structure S for use with POLYVAL to obtain error estimates on
predictions. If the errors in the data, Y, are independent normal with constant variance, POLYVAL will produce error bounds which
contain at least 50% of the predictions.
The structure S contains the Cholesky factor of the Vandermonde matrix (R), the degrees of freedom (df), and the norm of the
residuals (normr) as fields.
To find the time behavior of a ditribution assumed linear
p=polyfit(t,a,1)
To find for the error in the exponent p, you need to determine the quantity S of above:
[p, s]=polyfit(t,a,1)
Then, with polyval:
[y, delta] = polyval(p, t, s)
p_min=polyfit(t, y+delta,1)
p_max=polyfit(t,y-delta,1)
The error in p is the differnce between p_min and p_max
Mathematics
To compute the module of an angle (normalized to 360o).
t=mod(t,360)
Symbolic toolbox
Creating Symbolic Variables and Expressions
To create a symbolic variable:
x = sym('x')
To create more than one (more practical command):
syms a b c x (equivalent to a = sym('a'); b = sym('b') etc.)
To simplify a symbolic expression use simplify(f)
Example:
rho = sym('(1+sqrt(5))/2')'
(golden ratio)
f= rho^2- rho -1
(which returns
f =
(1/2+1/2*5^(1/2)^2-3/2-1/2*5^(1/2)
Then
symplify(f)
returns
0
Symbolic and Numeric Conversions
t = 0.1
sym(t,'f') returns a symbolic floating-point representation
'1.999999999999a'*2^(-4)
The 'r' option
sym(t,'r') returns the rational form
1/10
(default setting for sym, sym(t,'r') is equivalent to sym(t)).
A particular effective use of sym is to convert a matrix from numeric to symbolic form. E.g.
A = hilb(3)
which returns:
A =
1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000
By applying sym to A
A = sym(A)
We obtain
A =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
Other options of sym are e (returns the rational form of t plus the difference between the theoretical rational expression for t and its actual (machine) floating-point value in terms of eps (the floating-point relative accuracy. E.g.
sym(t,'e')
ans =
1/10+eps/40)
and d, which returns the decimal expansion of t up to the number of significant digits specified by digits. E.g .
digits(7)
sym(t,'d')
ans =
.1000000
Constructing Real and Complex Variables
syms x y real
z = x + i*y
returns a complex (z) variable. conj(z) returns:
x-i*y
Other examples:
conj(x) , expand(z*conj(z))
Yields:
x, x^2 +y^2
Creating a Symbolic Matrix
We can create a circulant matrix with elements a, b, and c, with the commands:
syms a b c
A = [ a b c; b c a; c a b];
which returns
A =
[ a, b, c]
[ b, c, a]
[ c, a, b]
Since A is circulant, the sum over each row and column is the same. E.g.
sum(A(:,1))
returns
ans =
a+b+c
The command sum(A(:,1)) == sum(A(:,2)) % This is a logical test.
returns
ans =
1
Now replace the (2,3) entry of A with beta and the variable b with alpha. The commands:
syms alpha beta;
A(2,3) = beta;
A = subs(A,b,alpha)
returns
A =
[ a, alpha, c]
[ alpha, c, beta]
[ c, a, alpha]
The Default Symbolic Variable
This is the variable used by default to differentiate, integrate, etc. symbolic expression. It is generally the letter that is closest to 'x' alphabetically. If there are two equally close, the letter later in the alphabet is chosen.
E.g.
syms x n
f = x^n;
diff(f) returns
ans =
x^n*n/x
To find the default symbolic variable use the command findsym. E.g.
findsym(f,1)
ans=
x
findsym(f,2)
ans=
n
Differentiation
To differentiate with respect to the default symbolic variable, use diff. E.g.
syms a x
f = sin(a*x)
diff(f)
ans =
cos(a*x)*a
To differentiate with respect to the variable a, type
diff(f,a)
ans =
cos(a*x)*x
To calculate the second derivative (with respect to x):
diff(f,x,2)
ans =
-sin(a*x)*a^2
We can also differentiate a symbolic matrix:
syms a x
A = [cos(a*x), sin(a*x); -sin(a*x),cos(a*x)]
A =
[ cos(a*x), sin(a*x)]
[ -sin(a*x), cos(a*x)]
diff(A)
ans =
[ -sin(a*x)*a, cos(a*x)*a]
[ -cos(a*x)*a, -sin(a*x)*a]
We can also perform differentiation of a column vector with respect to a row vector, like the Jacobian of a transformation. Consider the transformation from Euclidean (x,y,z) to sperical (r,l,f) coordinates:
syms r l f
x = r*cos(l)*cos(f); y =r*cos(l)*sin(f); z=r*sin(l);
J = jacobian([x;y;z],[r l f])
J =
[ cos(l)*cos(f), -r*sin(l)*cos(f), -r*cos(l)*sin(f)]
[ cos(l)*sin(f), -r*sin(l)*sin(f), r*cos(l)*cos(f)]
[ sin(l), r*cos(l), 0]
and the command
detJ = simple(det(J))
returns
detJ =
-cos(l)*r^2
simple returns the expression with the fewest possible number of characters.
Limits