* Image Processing Toolbox. The Image Processing Toolbox builds on MATLAB's numeric, signal processing, and visualization capabilities to provide a comprehensive system for image processing and algorithm development.
* MMLE3 Identification Toolbox. The MMLE3 Identification Toolbox is a specialized toolbox for use with MATLAB and the Control System Toolbox for the estimation of continuous-time state-space models from observed input-output data.
* Model Predictive Control Toolbox. The Model Predictive Control Toolbox is especially useful for applications involving constraints on the manipulated and/or controlled variables. For unconstrained problems, model predictive control is closely related to linear quadratic optimal control, but includes modeling and tuning options that simplify the design procedure.
* Mu-Analysis and Synthesis Toolbox. The Mu-Analysis and Synthesis Toolbox contains specialized tools for the analysis and design of robust, linear control systems, extending MATLAB to provide additional application-specific capabilities.
* Nonlinear Control Design. This toolbox provides a Graphical User Interface to assist in time-domain-based control design. With this toolbox, you can tune parameters within a nonlinear SIMULINK model to meet time-domain performance requirements. You can view the progress of an optimization while it is running. Optimization routines have been taken from the Optimization Toolbox.
* Neural Network Toolbox. This is a toolbox for designing and simulating neural networks and supports implementation of the perceptron learning rule, the Widrow-Hoff rule, and several variations of the backpropagation rule. Transfer functions included are hard limit, linear, logistic, and hypertangent sigmoid.
* Optimization Toolbox. This is a toolbox for linear and nonlinear optimization. It supports unconstrained and constrained minimization, minimax, nonlinear least squares, multi-objective, semi-infinite optimization, linear programming, quadratic programming, and the solution of nonlinear equations.
* Robust Control Toolbox. This is a toolbox for robust control system design and supports LQG/loop transfer recovery, H2, H0, and mu- control synthesis, singular value frequency response, and model reduction.
* Signal Processing Toolbox. This is a toolbox for digital signal processing (time series analysis). It includes functions for the design and analysis of digital filters, like Butterworth, Elliptic, and Parks-McClellan, and for FFT analysis (power spectrum estimation). It also includes some two-dimensional signal processing capabilities.
* Spline Toolbox. This is a toolbox for working with splines and is typically used for curve fitting, solution of function equations, and functional approximation.
* Statistics Toolbox. The Statistics Toolbox builds on the computational and graphics capabilities of MATLAB to provide: 1) statistical data analysis, modeling, and Monte Carlo simulation 2) building blocks for creating your own special-purpose statistical tools, and 3) GUI tools for exploring fundamental concepts in statistics and probability.
* Symbolic Math Toolbox. The Symbolic Math Toolbox contains functions for symbolic algebra, exact linear algebra, variable precision arithmetic, equation solving, and special mathematical functions. Its underlying computational engine is the kernel of Maple. The Extended Symbolic Math Toolbox augments the functionality to include Maple programming features and specialized libraries.
* System Identification Toolbox. This is a toolbox for parametric modeling. Identified models are in transfer function form (either z transform or Laplace transform) and state-space form (e.g., ARMA models or Box-Jenkins models).
* Chemometrics Toolbox. This toolbox contains a library of functions that allows you to analyze data based on chemometrics methods including multiple linear regression, classical least squares, inverse least squares, Q-matrix, factor based methods, principle component regression, and partial least squares in latent variables. There are also useful functions for plotting data.
* Frequency Domain System Identification Toolbox. This toolbox contains tools for accurate modeling of linear systems with or without delay. The models are transfer functions in s-domain or in z-domain. The procedures include excitation signal design, data preprocessing, parameter estimation, graphical presentation of results, and model validation (tests, uncertainty bounds, modelling errors).
* Hi-Spectm Toolbox. The Hi-Spectm Toolbox, a Partner Series Toolbox, was created by Jerry Mendel, C.L. (Max) Nikias, and Ananthram Swami. The Hi-Spec Toolbox is a collection of MATLAB routines whose primary features are functions for:
* Higher-order spectrum estimation either by conventional or parametric approaches
* Magnitude and phase retrieval
* Adaptive linear prediction
* Harmonic retrieval and quadratic phase coupling
* Time-delay estimation and array signal processing
Toolkits are also available from The Mathworks, Inc. Toolkits are colections of M-files associated with books. These are available from the publisher or from ftp.mathworks.com in /pub/books.
* Control of Spacecraft and Aircraft Toolkit. This is a package of MATLAB programs to demonstrate the concepts discussed in the text "Control of Spacecraft and Aircraft," by Arthur E. Bryson. (1994) Princeton University Press, 1994.
* Signal Processing Examples Toolkit. This is a package of MATLAB programs to demonstrate the concepts discussed in the text "Computer-Based Exercises for Signal Processing Using MATLAB," by C. Sidney Burrus, James H. McClellan, Alan V. Oppenheim, Thomas W. Parks, Ronald W. Schafe, and Hans Schuessler. (1994) Prentice Hall.
* Delta Toolkit. This is a toolkit for analysis using the delta transform, an approach to unifying continuous and discrete systems theory without use of the z transform. It is available free to purchasers of "Digital Control and Estimation: A Unified Approach," by Graham Goodwin and Rick Middleton.
* Numerical Methods for Physics Toolkit. This is a toolkit for which demonstrates the concepts discussed in the text "Numerical Methods for Physics Using MATLAB," by Alejandro Garcia. (1994) Prentice Hall. It is available free to purchasers of this text.
* Numerical Methods for Mathematics, Science and Engineering Toolkit. This is a toolkit for which demonstrates the concepts discussed in the text "Numerical Methods for Mathematics, Science and Engineering, Second Edition," by John H. Matthews. (1994) Prentice Hall. It is available free to purchasers of this text.
* Introduction to Linear Algebra Toolkit. This is a package of MATLAB programs to use with MATLAB in learning and experimenting with linear algebra. The toolbox is coordinated with the text: "Introduction to Linear Algebra," by Gilbert Strang. (1993) Wellesley-Cambridge Press Box 812060 Wellesley MA 02181.
* Templates Toolkit . The M-files were created to supplement "Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods," by Richard Barrett, Michael Berry, Tony Chan, James Demmel, June Donato, Jack Dongarra, Victor Eijkhout, Roldan Pozo, Charles Romine, and Henk van der Vorst (SIAM, 1994).
* Digitale Signalverarbeitung, Grundlagen und Anwendungen, Beispiele und Uebungen Toolkit. This is a toolkit for which demonstrates the concepts discussed in the text "Digitale Signalverarbeitung, Grundlagen und Anwendungen, Beispiele und Uebungen mit MATLAB," by Daniel Ch. von Grunigen. It is available free to purchasers of this text.
* support@mathworks.com Technical support
* suggest@mathworks.com Product enhancement suggestions
* bugs@mathworks.com Bug reports
* doc@mathworks.com Documentation error reports
* subscribe@mathworks.com Subscribing user registration
* service@mathworks.com Order status, renewals, passcodes
* info@mathworks.com Sales, pricing, general info.
* digest@mathworks.com Submission and questions for the digest
* Ability to produce hpgl format files
* Ability to import graphs into Adobe Illustrator '88
* Ability to save a figure and load it back into MATLAB
* Better, faster graphics
* DDE capability for the PC
* Online documentation for UNIX systems
* International Character Support (limited)
* Many memory leak fixes
Platform Loops LU Sparse 3-D 2-D IBM RS 1.38 0.67 1.93 2.60 1.78 6000/590 HP 735 1.35 1.34 2.52 2.43 2.14 SPARC 2.18 1.94 3.41 2.73 2.53 20/62 DEC Alpha 2.88 2.58 2.68 5.67 4.22 3500 SGI Indy 3.55 2.40 4.12 5.20 5.25 R4000 SPARC 3.48 2.89 4.78 5.20 5.23 10/41 PC 4.69 3.96 3.45 7.24 6.28 Pentium/90 Mac Power 4.78 3.99 3.53 7.77 7.91 PC 8100 SPARC 2 10.00 10.00 10.00 10.00 10.00 PC 486 5.59 9.96 8.26 13.70 12.77 DX2/66 PC Laptop 14.10 15.40 13.20 30.50 25.00 486 DX2/40 Mac Quadra 26.30 18.40 26.60 36.50 29.50 700 Mac Power 34.00 84.60 74.80 65.40 65.40 Book 165C
SIMULINK has added the following features in version 1.3:
* Vectorization of blocks
* Scalar expansion of inputs
* Automatic routing of block connections
* Wide vector lines
* Sample time coloration of model
* Enhanced S-functions
* Many new blocks!
The second way to call MATLAB routines from your program is to use MATLAB as a computational engine. A set of subroutines is provided that allows you to start MATLAB, send data and commands to it, get data back, and terminate MATLAB. This way you can call any MATLAB routine from your FORTRAN or C function.
Macintosh version (disks and user guide): ISBN #0-13-184987-5
MS-Windows version (disks and user guide): ISBN #0-13-184995-6
It includes the Signals and Systems Toolbox, a collection of routines from the professional Signal Processing Toolbox and the Control System Toolbox; if you're familiar with the previous student edition, the toolbox is enhanced from the previous one. It has a number of filter design tools, including Parks-McClellan. In addition, the student edition includes a version of the Symbolic Math Toolbox, based on the Maple V compute kernel.
The Mac Student Edition of MATLAB does not include native PowerMac support because our PowerMac version was not available several months ago when we had to send the Student Edition master off to Prentice-Hall for manufacturing.
We have every intention of providing Macintosh Student Edition users with native PowerMac support. This will happen after we release the professional version of MATLAB for the PowerMac and when we get the new Student Edition master disks into the Prentice-Hall pipeline.
This happens from time to time, depending on your machine, because of the way MATLAB tries to compensate for the Math Coprocessor (which is not required). There is only one version of Student Edition for PC's. Here are two fixes for the problem:
OPTION 1:
Edit the matlab.bat file, add the following line above the pcmatlab line, set N087=1, so it will look like this:
set NO87=1 (there are no spaces on either side of the =, and that is a letter O not the number 0.)
pcmatlab .....
OPTION 2:
1. Go to the MATLAB bin directory (cd matlab/bin)
2. Copy PCMATLAB.EXE to PACMATLAB.ORG.
3. Rename PCMATLAB.EXE to PCMATLAB.DAT (using the DOS ren command)
4. At the DOS prompt, type debug pcmatlab.dat and press enter. You will be at the left margin with a minus sign.
5. At the minus, type rcs and it will return CS xyyy where x and y are numbers. You will then be at the colon prompt.
6. At the colon prompt, hit return and you'll get back the minus prompt.
7. At the minus prompt, enter e zyyy:11 where z=x+3, then press return. You should get back zyyy:0011 25.
8. Immediately following zyyy:0011 25. type D followed by a space. This should return 3C. on the same line.
9. Immediately following 3C. type 3F followed by a space. This should return FF. on the same line.
10. Immediately following FF., type 0 (zero) and press return. You will be back at the minus prompt.
11. Enter w and press return. The text Writing 51F92 bytes will be displayed and you will be back at the minus prompt.
12. Enter q and press return. You will be back at the DOS prompt.
13. Rename PCMATLAB.DAT to PCMATLAB.EXE (using the DOS ren command).
Removing the last line %%EOF from the eps-file.
Use the pstoepsi filter from Doug Crabill (dgc@cs.purdue.edu).
Use bbps and GhostScript. bbps.shar is available via anonymous ftp on csi.jpl.nasa.gov. You'll need to get GhostScript from your nearest GNU ftp site.
Also, there is a technical note written on this topic available on our anonymous ftp server. It can be found in pub/tech-support/tech-notes/mat4.txt.
Try the following:
set OLDDISPLAY=$DISPLAY
unsetenv DISPLAY
nohup matlab < filein > fileout &
setenv DISPLAY $OLDDISPLAY
where filein is the M-file you want to run and fileout is the file you want the output to go to. To set this up as a C shell script, write a file called matbat as:
#!/bin/csh set OLDDISPLAY=$DISPLAY
unsetenv DISPLAY nohup matlab < $1 > $2 &
setenv DISPLAY $OLDDISPLAY
To run this file, issue the command as:
matbat infile outfile
In MS Windows: You need to set the ratio for applications running in the foreground as opposed to running in the background. This ratio will determine how well you can run MATLAB in the background. To set this ratio, go into 386 Enhanced in your Windows Control Panel. You can change your ratio here.
Make sure that you don't have any other large applications running in the background and that there aren't a lot of other people logged onto your machine. These things can also cause MATLAB to run slowly.
set(0,'DefaultFigurePosition',[5,5,505,405])
set(0,'DefaultFigureColor',[0,0,0]) %%N.B this has side
%%effects.
set(0,'DefaultAxesFontName','times')
set(0,'DefaultTextFontName','times')
set(0,'DefaultAxesFontSize',12)
set(0,'DefaultTextFontSize',12)
or from Brian Fitzgerald <fitzgb@mml0.meche.rpi.edu> ...
figure(1)
set(1,'Position', [ 10 10 610 610])
There is a colormap command in MATLAB, which allows you to set your colormap to 10 different sets of colors. For example, colormap cool gives you shades of cyan and magenta while colormap jet gives you shades of blue.
You can set a limit on your colors using the functions caxis, cmin, and cmax. These functions let you define the range of colors you will be using.
>> lookfor fourier
FFT Discrete Fourier transform.
FFT2 Two-dimensional Fast Fourier Transform.
IFFT Inverse discrete Fourier transform.
IFFT2 Two-dimensional inverse discrete Fourier transform.
FOURIER Graphics demo of Fourier series expansion.
DFTMTX Discrete Fourier transform matrix.
There are other undocumented functions in directories other than /demos. Some of them are "worker" functions that are unlikely to be used directly; they are simply called by other functions. A few, like comet and comet3, were written after the MATLAB User's Guide was sent to the printer. You should always check the README file for late-breaking news and information.
seed=(7^5*seed)mod(2^31-1)
If you want to set the initial seed to an random value, type the following at the MATLAB prompt:
rand('SEED',fix(100*sum(clock)))
This will use the clock to set the seed.
Bourne shell example: (file called atfile.sh)
TERM=; export TERM
matlab > inline.out << EOF
a = [1 2]
quit
EOF
Sample at command on Sun: (-s says use the Bourne shell)
% at -s now + 1 min atfile.sh
C shell example: (file called atfile.csh)
setenv TERM
matlab >! inline.out << EOF
a = [1 2]
quit
EOF
Sample at command on Sun:
% setenv SHELL '/bin/csh -f'
% at now + 1 min atfile.csh
% setenv SHELL /bin/csh
In summary,
Define TERM in the script before you call MATLAB and make it part of the environment. Be sure that the right shell is used to execute the script. If your script is a C shell, you must do the SHELL change in order not to get any extra mail messages from the job. remember that -f means that your .cshrc file will not be executed before you run the script. So, you cannot use any of the parameters set in the script.
The Student Edition version is limited to variables of size 32 by 32.
function position = index3(d,i,j,k)
%INDEX3 POSITION = INDEX3(d,i,j,k) index a 3-D array
% d is a vector that specifies the dimensions on the array
position = (i+(j-1)*d(2)+(k-1)*d(2)*d(3));
The following is an example of how you might use this function.
D = [9 9 9]; % D give the dimensions as 9x9x9
A = 1:(9*9*9); % A is where your 3D data is % stored
A(index(D,5,4,4)) = 77; % Write to it
B = A(index(D,5,4,4)); % Read from it
You can create N-dimensional arrays with different limits on each dimension. The main difference is that you would change how the offset is indexed through your matrix. Each additional dimension would require a corresponding offset. You can add error checking for the indices to make sure you do not go out of bounds.
To initialize a matrix with values "a" in the first row and values "b" in the second row, do the following:
[a(1,ones(1,m)) ; b(1,ones(1,m))]
csi.jpl.nasa.gov as pub/matlab/util/matlab-mode.el or,
ftp.mathworks.com as /pub/contrib/tools/matlab-mode.el.
eval(['save ', name]);
eval(['load ', name]);
name = 'myfigure.ps';
eval(['print ',name]);
ftp.mathworks.com in /pub/contrib/optim/fsolve35.
Example: x,y,z => irregularly spaced data
xmin=min(x);
ymin=min(y);
xmax=max(x);
ymax=max(y);
xi=xmin:0.02*(xmax-xmin):xmax;
yi=ymin:0.02*(ymax-ymin):ymax;
zi=griddata(x,y,z,xi',yi);
contour(xi,yi,zi)
x = 1:10;
y = exp(x); % create exponential data to be fitted
c = polyfit(x,y,9); % generate coefficients for a fitted % polynomial of degree 9
yfit = polyval(c,x); % evaluate the polynomial at x
plot(x,y,'yo',x,yfit,'r-') % plot the results
There is a technical note on fitting a function to data using leastsq which can be found on the ftp server under pub/tech-support/tech-notes/math4.txt.
To find out more, take a look at the online help available for these functions. Also, there is a technical note describing how to load and save data in MATLAB which can be found on the ftp server under pub/tech-support/tech-notes/io1.txt.
= ode45('yprime', T0, Tfinal, Y0)
where the inputs to the function are:
F - String containing name of user-supplied problem description.
Call: yprime = fun(t,y) where F = 'fun'.
t - Time (scalar).
y - Solution column-vector.
yprime - Returned derivative column-vector; yprime(i) = dy(i)/dt.
t0 - Initial value of t.
tfinal- Final value of t.
y0 - Initial value column-vector.
tol - The desired accuracy. (Default: tol = 1.e-6).
trace - If nonzero, each step is printed. (Default: trace = 0).
The call to quad and quad8 is as follows:
Q = quad8(F,A,B,TOL,TRACE)
However, if you want to pass extra parameters to the function, do as follows:
Q = quad8('F',A,B,TOL,TRACE,P1,P2,...)
This allows coefficients P1, P2, ... to be passed directly to function F:
function g=f(a,b)
G = F(X,P1,P2,...).
To use default values for tol or trace, you can pass in the empty matrix.
For more information, take a look at the technical note on this topic. It can be found on the ftp site in pub/tech-support/tech-notes/math1.txt.
Here are some additional system specific tips:
MS-Windows: Increase the swap space by opening the Control Panel, double-clicking on the 386 Enhanced icon, and pressing the Virtual Memory button.
Macintosh: Under Multi-Finder, change the application memory size by using Get Info on the program icon. Under Single-Finder, install more memory.
VAX/VMS: Ask your system manager to increase your working set.
UNIX: Ask your system manager to increase your swap space.
OPTION 1: Edit the matlab.bat file, add the following line above the pcmatlab line, set N087=1, so it will look like this:
set NO87=1 (there are no spaces on either side of the =, and that is a letter O not the number 0.)
pcmatlab .....
OPTION 2:
Go to the MATLAB bin directory (cd matlab/bin)
Copy PCMATLAB.EXE to PACMATLAB.ORG.
Rename PCMATLAB.EXE to PCMATLAB.DAT (using the DOS ren command)
At the DOS prompt, type debug pcmatlab.dat and press enter. You will be at the left margin with a minus sign.
At the minus, type rcs and it will return CS xyyy where x and y are numbers. You will then be at the colon prompt.
At the colon prompt, hit return and you'll get back the minus prompt.
At the minus prompt, enter e zyyy:11 where z=x+3, then press return. You should get back zyyy:0011 25.
Immediately following zyyy:0011 25. type D followed by a space. This should return 3C. on the same line.
Immediately following 3C. type 3F followed by a space. This should return FF. on the same line.
Immediately following FF., type 0 (zero) and press return. You will be back at the minus prompt.
Enter w and press return. The text Writing 51F92 bytes will be displayed and you will be back at the minus prompt.
Enter q and press return. You will be back at the DOS prompt.
Rename PCMATLAB.DAT to PCMATLAB.EXE (using the DOS ren command).
handle=plot(x,y)
get(handle,'PropertyName')
set(handle,'PropertyName','PropertyValue')
Two common handles are gca and gcf which stand for 'get current axes' and 'get current figure', respectively. If you use gca or gcf as the handle in your get or set statement, you will be able to change the properties of the current figure or current axes without previously defining their handles.
For more information, look at the MATLAB technical note written on this topic. It can be found on the ftp site in pub/tech-support/tech-notes/gr12.txt.
set(handle)
This returns a list of all the properties associated with that object as well as each property's optional settings. The settings in { } are the default settings.
h=get(object's_handle,'Parent')
To set the default, type the following:
set(h,'DefaultObjectPropertyName','PropertyValue')
Don't put any spaces in the DefaultObjectPropertyName expression. A good example of how to do this is the following:
set(gca,'DefaultLineLineWidth',10)
Any line you plot after this statement will have a line width of 10.
set(gca,'DefaultLineLineWidth','factory')
How do I change the font of labels?
When you change the default font name and font size, the factory settings will still be used when drawing the title and lables on the screen. Following is a modified xlabel, ylabel, zlabel, and title to recognize changes to the default FontName and FontSize; however, it would be just as easy to have it recognize changes to all the default text font properties. Below are the revised programs:
<------- XLABEL.M ------->
function xlabel(string)
% XLABEL X-axis labels for 2-D and 3-D plots.
% XLABEL('text') adds text below the X-axis on the current % axis.
%
% See also YLABEL, ZLABEL, TITLE, TEXT.
% Copyright (c) 1984-92 by The MathWorks, Inc.
h = get(gca,'xlabel');
ht = get(text,'fontname');
hs = get(text,'fontsize');
if isempty(h)
h = text('HorizontalAlignment','center');
set(gca,'xlabel',h);
end
set(h,'string',string,'fontname',ht,'fontsize',hs);
<------- YLABEL.M ------->
function ylabel(string)
% YLABEL Y-axis labels for 2-D and 3-D plots.
% YLABEL('text') adds text beside the Y-axis on the current % axis.
%
% See also XLABEL, ZLABEL, TITLE, TEXT.
% Copyright (c) 1984-92 by The MathWorks, Inc.
h = get(gca,'ylabel');
ht = get(text,'fontname');
hs = get(text,'fontsize');
if isempty(h)
h = text;
set(gca,'ylabel',h);
end
set(h,'string',string,'fontname',ht,'fontsize',hs);
<------- ZLABEL.M ------->
function zlabel(string)
% ZLABEL Z-axis labels for 3-D plots.
% ZLABEL('text') adds text above the Z-axis on the current % axis.
%
% See also XLABEL, YLABEL, TITLE, TEXT.
% Copyright (c) 1984-92 by The MathWorks, Inc.
h = get(gca,'zlabel');
ht = get(text,'fontname');
hs = get(text,'fontsize');
if isempty(h)
h = text;
set(gca,'zlabel',h);
end
set(h,'string',string,'fontname',ht,'fontsize',hs);
<------- TITLE.M ------->
function title(string)
% TITLE Titles for 2-D and 3-D plots.
% TITLE('text') adds text at the top of the current axis.
%
% See also XLABEL, YLABEL, ZLABEL, TEXT.
% Copyright (c) 1984-92 by The MathWorks, Inc.
h = get(gca,'title');
ht = get(text,'fontname');
hs = get(text,'fontsize');
if isempty(h)
h = text('horiz','center');
set(gca,'title',h);
end
set(h,'string',string,'fontname',ht,'fontsize',hs);
For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr2.txt.
set(h,'FontName','font')
where h is the handle to the text object, and font is the name of the font you wish to use.
For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr6.txt.
set(gca,'FontStyle','courier')
will change the font of x and y tick labels before they are created. To change the font of existing labels, do the following:
h=get(gca,'Xlabel');
set(h,'FontName',font);
For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr10.txt.
h=text(x,y,'string')
set(h,'FontName','courier');
or
set(gca,'FontName','symbol');
text(x,y,setstr(num));
where x and y are the coordinates on the graph where you want to place the Greek symbols, and num is the value from the list of 0-255 characters from the symbol font. To display a table of the symbol font, you can use the following M-file called chart.m.
function chart( fontname )
% CHART Show ANSI-chart like display of characters MATLAB
%can produce.
% CHART( 'fontname' ) will put up a figure
% window with all 255
% characters of the named font in a 16x16 grid.
% Close figure when done, it creates 256 text
% objects. You may want
% that memory back!
% Chuck Packard, The Mathworks, Inc., 25 Jan 93
% This is an unsupported, purely for example, M-
% file.
%
%
% TO USE THIS CHART:
% USE SETSTR( VALUE), WHERE VALUE=( (16*XCOORD)+YCOORD)
%
%
% make a new figure and axis
% (I'm assuming you want to keep the current graph in the
% gcf.)
%
figure;
axis([-1 16 -1 16])
ax = gca;
%
%set font to be used
%
set(ax, 'DefaultTextFontName', fontname )
%
%some other Handle Graphics settings, written out in
%full.
%See manual for more info.
%
set(ax, 'YDir', 'Reverse', 'Box', 'on')
set(ax, 'YTick', 0:15, 'XTick', 0:15)
set(ax, 'DefaultTextHorizontalAlignment', 'Center')
set(ax, 'DefaultTextVerticalAlignment', 'Bottom')
%
%not vectorized like all 'good' MATLAB M-files, but
%easier to understand!
%
x = reshape( 0:255, 16, 16 );
for h=1:16
for v=1:16
text(h-1,v-1,setstr(x(v,h)));
end
end
set(h,'LineWidth',size)
where h is the handle to a line and size is the width you want. The default line width is 0.5.
function prtlines(a1,a2,a3,a4,a5)
% PRTLINES is a front-end to PRINT which converts
% solid lines to various line styles for graphical
% output. The change is transparent to the user.
% Non-solid lines are not affected.
%
% PRTLINES is used in the same manner as PRINT.
%
% The default line styles are:
%
% '. '
% 'o '
% 'x '
% '+ '
% '- '
% '* '
% ': '
% '-.'
% '--'
%
% The line style can be changed by editing the file
% and changing the 'styles' array.
%
% SEE ALSO: PRINT, Properties of LINE
% Written by John L. Galenski III
% All Rights Reserved 10/14/93
% LDM101493jlg
%% PRTLINES is an M-file developed by me for my own
%% personal use, and therefore, it is not supported
%% by The MathWorks, Inc., or myself. Please direct
%% any questions or comments to johng@mathworks.com.
% Create the array of line styles.
styles = [
'. '
'o '
'x '
'+ '
'- '
'* '
': '
'-.'
'--'
];
% Get the Children of the Figure.
a = get(gcf,'children');
% Check the Children of 'a'. If they are
% solid lines, then change their LineStyle
% property.
for j = 1:length(a)
l = sort(get(a(j),'children'));
X = 0;
Add = 0;
for i = 1:length(l)
if strcmp( 'line', get(l(i), 'type' ))
if strcmp(get(l(i),'linestyle'),'-')
X = X + 1;
LINE = [LINE;l(i)];
SI = rem(X,length(styles));
if SI == 0
Add = 1;
end
set(l(i),'linestyle', styles(SI+Add,:));
end
end
end
end
% Construct the PRTCMD.
PRTCMD = 'print';
for x = 1:nargin
PRTCMD = [PRTCMD,' ',eval(['a',int2str(x)])];
end
% Discard the changes so that the Figure is not
% updated.
drawnow discard
eval(PRTCMD)
% RESET THE LINESTYLES
set(LINE,'linestyle','-')
% Discard the changes so that the Figure is not
% updated.
drawnow discard
set(gca,'ColorOrder',A)
where A is an RGB vector of any length.
pos=[x_position, y_position, width, height];
set(gcf,'Position',pos)
set(gca,'Visible','off')
This is very useful if you want to place text in the figure window with respect to the borders of the figure, rather than with respect to the axes.
whitebg
To change the color of your figure window to something other than black or white, type the following:
set(gcf,'Color','red')
print -dmfile <filename>
creates two files, filename.m and filename.mat. The M-file contains the necessary object creation and set commands to reproduce the figure. The generated MAT-file also contains the figure data. Handle values are not maintained.
in the EPS file. When you send the Word file to a PostScript printer that gray box with not be drawn, the PostScript image will be rendered.
h=uicontrol('Style','PushButton','String','title',...
'CallBack','disp(''hello'')')'
When you push on the button, hello will be displayed in the MATLAB workspace. The most efficient way to write a CallBack is to make the CallBack a function. That way, the function is stored in RAM and will execute more quickly if you are going to be using the button often.
h=waterfall(peaks);
set(h,'edgecolor','w')
This will make the edgecolor for the whole waterfall a constant color and allow printing as well as display.
function aspect3(x,y,z)
v = get(gca,'xform');
d = diag([x y z 1]);
set(gca,'xform',v*d);
% Place a gray PCOLOR of PEAKS and hsv SURF of PEAKS in
% the same plot.
clf
hold off
% Set the colormap
colormap([gray(30);hsv(30)])
% Generate the data
= peaks(30);
% Create the Cdata for the PCOLOR and SURFACE plot.
% The Cdata for each plot should be contiguous, and
% not overlap. This will guarantee that they use
% different regions of the colormap.
cd1 = z + abs(min(min(z)));
cd2 = cd1 + max(max(cd1)) + 1;
% Place the PCOLOR
P = pcolor(cd1);
shading interp
% Change the location so that it will be visible when
% the SURFACE is drawn
set(P,'zdata', -30*ones(size(get(P,'zdata'))))
hold on
% Place the SURFACE plot
S = surf(1:30,1:30,z,cd2);
% Change the location so that it does not overlap the
% PCOLOR
%set(S,'zdata',15+get(S,'zdata'))
% Change the Clim used by AXES
set(gca,'clim',[min(min(cd1)), max(max(cd2))])
% Make sure that the VIEW and AXES limits are correct
view(3)
axis([1 30 1 30 -30 30])
% Rules that you need to follow when doing this.
%
% 1) The Cdata values for each plot should
% not overlap.
%
% 2) The range between the minimum and maximum
% values in Cdata should be the same for each
% plot.
%
% 3) The Cdatas must be contiguous.
%
% 4) Set Clim for AXES to range from the
% smallest and largest values of the 2 Cdatas.
pcolor is a surface plot and its CData is scaled into the colormap. Each element of the CData corresponds to a vertex in the plot. Therefore, the number of rectangles in pcolor is always one row and column smaller than the actual data.
If you are working on a Macintosh or a PC, you can also print from the File pulldown menu on the Figure window (for Macintoshes, make sure the Figure window is the selected window).
If you are working on a Macintosh or a PC, you can print from the File pulldown menu, just as you would print a figure.
The makers of GhostScript can be contacted at the following: Phone: 617-876-3296 Email: gnu@prep.ai.mit.edu
Quickest way:
Create a directory called C:\GS
Copy all files in the directory $MATLAB\GHOSTSCR\BIN, $MATLAB\GHOSTSCR\PS_FILES, and $MATLAB\GHOSTSCR\FONTS to C:\GS (where $MATLAB represents the MATLAB root directory)
Copy the PostScript file to C:\GS
CD to C:\GS
Execute the command GS386 <postscriptfilename>
where <postscriptfilename> is the whole name, including the .ps extension. If for some reason this doesn't work, try
DOS4GW GS386 <postscriptfilename>.
Clean but somewhat cumbersome:
CD to the $MATLAB\GHOSTSCR\BIN directory
Execute the command
GS386 -I..\PS_FILES -I..\FONTS <postscriptfilename>
where here <postscriptfilename> represents the full path name to the postscript file.
Clean and easy but more permanent:
Add $MATLAB\GHOSTSCR\BIN to your DOS path.
In the AUTOEXEC.BAT file, set an environment variable called GS_LIB as
follows:
set GS_LIB = $MATLAB\GHOSTSCR\PS_FILES;$MATLAB\GHOSTSCR\FONTS
(where $MATLAB is replaced by the MATLAB root directory.) Now to use GhostScript you can type gs386 <postscriptfilename> from any directory.
print -<device> <filename>
/Times-Roman findfont
dpi2point mul 0 0 10 dpi2point mul neg 0 0]
The /Times-Roman is the font name you can change. The occurrence of 10 on the second line is the point size.
function printsys(sys)
open_system(sys);
blocks=get_param(sys,'blocks');
= size(blocks);
for i=1:r
if( get_param([sys,'/',blocks(i,:)],'blocks')~=[] )
open_system([sys,'/',blocks(i,:)])
%disp(blocks(i,:))
print('-s')
end
end
close_system(sys)
This has been fixed in 4.2.
This is more of a problem with Windows than MATLAB. Windows will not reallocate system resources even after you have exited the application. You have to exit Windows and then restart Windows in order to get all of the system resources back.
This can be reproduced both from MATLAB and from MS EXCEL .
There is no clean solution to this problem other than printing to a file first and then sending the file to the printer.
Microsoft anticipates that Windows 4.0 will do a better job in handling system resources.
So that axis labels and tick mark labels do not overwrite each other, they are always some absolute distance from the axis line. The one caveat is that axis position is relative to the size of the figure and, when rendering to paper, the PaperPosition. When you've got a really small figure or have set the PaperPosition, the axis is very close in absolute coordinates (i.e., it's only 1/2" away rather than 3/4" from the edge of the window or the clipping edge of PaperPosition). The same thing can be seen by making the window really small.
A possible work around:
set(gca,'pos',[.2 .2 .7 .7],'units','norm')
Then adjust your output size to accommodate.
Most other software packages break the lines before presenting them to the printer--we do not. You need to use the GhostScript drivers or use PCL 5, which supports LaserJet 4's and up.
PCL 5---Laser jet 4
PCL 4---Laser jet 4,3
PCL 3---Laser jet 4,3,2
PCL 2---Laser jet 4,3,2,1
In version 4.2 of MATLAB, you have the option of using the Windows/printer drivers to get broken lines but the lines will be thinner. This is a trade off because you get really good fonts from the windows drivers but thin lines and you get less than perfect fonts from the GhostScript drivers but thicker lines. See page 84 of the 4.2 Release Notes.
UNIX Workaround:
Use the command capture, which captures the current figure into a matrix, and then displays it in another figure window using the image command. The new image can then be printed normally (but the uicontrols in the image don't work, obviously). Since this method involves printing a bitmap image of the screen, the printout may not have as high a print resolution as the hardcopy results of the print command.
PC Workaround:
There is no capture command for the PC version. One workaround is to use Windows handling of PRINTSCREEN. Select the figure that you want to print and press Alt-PrintScreen. A copy of the current window will be placed on the clipboard. This image can be pasted into another application for printing. One undesirable attribute of this workaround is that the Windows window titles and menus are included in the image. These sections of the image can be "cut" using Windows PaintBrush program.
To increase the number of surface faces, use griddata:
[xi,yi,zi] = griddata(x,y,z,0:.1:10,0:.1:100)
where x, y, and z are your original data, 0:.1:10 and 0:.1:100 are your new and increased ranges for x and y.
Then use xi, yi, and zi in your surface command.
For more information, see the MATLAB technical note written on this topic. It is located on the ftp site in pub/tech-support/tech-notes/gr1.txt.
set(0,'DefaultFigurePaperType','A4')
To obtain a list of the available paper types...
set(0,'DefaultFigurePaperType')
The paper type must be set at the beginning of every MATLAB session unless you place it into the startup.m file.
You have demo passcodes (DEMO is located at the end of your encryption codes in your license.dat file)
You have a CPU locked Multi-User License (your hostid is located at the end of your encryption codes in your license.dat file and you have more than key). See page 9 of your Installation Guide if you are running on a VAX or page 1-14 if you are running on a UNIX system.
Install MATLAB from the tape onto each machine, using the install option for STANDALONE/SERVER machines.
For any client machines of the DEC and SUN, make sure the MATLAB client DEC machines have their matlab command access $MATLAB/bin/matlab on the DEC platform. Likewise, SUN MATLAB client machines should have their matlab command access $MATLAB/bin/matlab on the SUN platform.
Decide which machine is the license server. In this example we will consider the DEC machine to be the license server.
The DEC license file should contain the DEC lmhostid, the DEC lm_matlab vendor daemon and passcodes based on the DEC lmhostid.
In the SUN $MATLAB/etc directory, create a link for the license.dat file to point to the DEC $MATLAB/etc/license.dat.
Start the license manager from the DEC license server machine.
Keep in mind that for different platforms to work together, they must be using compatible versions of the license manager. For example, if you have V3.5j on the SUN, you cannot combine it with V4.1 for the DEC since they contain incompatible versions of the license manager. More specifically, the SUN MATLAB will call lmgrd on the DEC and place it in an incompatible state. It will not be able to run properly.
----------------------------------------------------------------------------
#License file for use with FLEXlm version 2.4c.
SERVER pooh 55419ab7 1705
SERVER piglet 554251b8 1705
SERVER rabbit 52006ac1 1705
DAEMON MLM /usr/local/matlab/etc/lm_matlab
FEATURE MATLAB MLM 1 01-jun-2012 99 6B283ACADCE90BE190B7 ""
FEATURE SIMULINK MLM 1 01-jun-2012 99 EB689A7AE885CDB2E0A3 ""
---------------------------------------------------------------------------
To bring up the three license managers interactively, do the following after installation.
Login to pooh. Become root. cd /usr/local/matlab/etc. Run lmstart.
Login to piglet. Become root. cd /usr/local/matlab/etc. Run lmstart.
Login to rabbit. Become root. cd /usr/local/matlab/etc. Run lmstart.
To have the license manager daemons started at boot time, follow the directions in the Installation Guide to place the Bourne shell code fragment into the appropriate boot script.
The /etc/lmboot link must exist on each of the servers. To create this link on a given server, first login to the server and then, as root, run:
# $MATLAB/etc/lmboot -s
where $MATLAB is the location of the MATLAB root directory.
Please note that at least two of the machines must always be running in order to create a network quorum. If only one of the three machines is running, no licenses will be available until a second server regains a running status.
The order of the servers is also important. The first server will be the primary server and if this machine fails, the primary server will be designated as the next server listed in the license file.
You must submit all three servers' hostids in order for the passcodes to be be properly generated for this configuration.
V2.4c of the license manager offered the option to enable multiple FEATURE lines of the same name into one license.dat file.
For this to work, it is necessary to place all the floating license FEATURE lines before all the node-locked FEATURE lines.
To start other vendors' daemons you must create:
A merged license.dat file with all the DAEMON and FEATURE lines associated with each vendor daemon.
A modified $MATLAB/etc/lmboot script. After installation the lmboot script needs to be modifed to know about each additional vendor daemon in the license file. This is so that the temporary license file in /usr/tmp can be created correctly.
This example demonstrates what needs to be done. Consider having both MATLAB and another vendor's daemons started by MATLAB's license manager daemon with the following license file:
----------------------------------------------------------------------------
#License file for use with FLEXlm version 2.4c.
SERVER radical 52201985 1700
#
DAEMON MLM /usr/local/matlab/etc/lm_matlab
FEATURE MATLAB MLM 1 01-aug-1995 3 6B486F9FDB9F99083820 ""
FEATURE SIMULINK MLM 1 01-aug-1995 3 8B38FF3F695F028F93A8 ""
FEATURE Control_Toolbox MLM 1 01-aug-1995 3 2B18BFEF0BB457E414B5 ""
#
DAEMON XXX /usr/local/XXX/license/bin/XXX
FEATURE XXX XXX 3.100 01-aug-1995 1CBB4ACD78C0C77ABE123 ""
---------------------------------------------------------------------------
You need to remember the DAEMON names when making the code changes. In this case the only additional DAEMON name is XXX.
Below is a Bourne shell code section from lmboot. The part between the
"======" lines must be modifed. For each DAEMON you must add three lines such as:
NAME)
ln -s $daemonPath /usr/tmp/$marker.vd$ndaemon
;;
The only thing that should change is NAME. It must be the name of the DAEMON. For PVI it would be
PVI)
ln -s $daemonPath /usr/tmp/$marker.vd$ndaemon
;;
Note that these lines for PVI are already shipped in the script, except the lines are commented out. To activate them simply remove the # or comment character from the beginning of the lines as indicated below. If there are additional daemons, then three more lines for each daemon must be added.
In order for the process command names given by the ps command to look the same across platforms, the symbolic link created in the three-line script section above should refer to a binary daemon program, not a script. This means the daemon path given by the third field of the DAEMON line (referred to as $daemonPath in the script) should be a path to a binary program. Note that for MATLAB this is not true. So a special value for the daemon path which refers directly to the binary is used.
#
#Create temporary license.dat file by copying and modifying the original file
#
rm -f /usr/tmp/$marker.dat > /dev/null 2>&1
rm -f /usr/tmp/$marker.vd* > /dev/null 2>&1
ndaemon=0;
(while read line
do
field1=`echo $line | awk '{print $1}'`
if [ "$field1" = "DAEMON" ]; then
daemonName=`echo $line | awk '{print $2}'` # field 2
daemonPath=`echo $line | awk '{print $3}'` # field 3
ndaemon=`expr $ndaemon + 1`
case "$daemonName" in
# Always assume $MATLAB/etc/$Arch/lm_matlab
# Must use the binary - NO SCRIPTS
ln -s $MATLAB/etc/$Arch/lm_matlab /usr/tmp/$marker.vd$ndaemon
;;
#============================================================
# ADD OTHER DAEMONS HERE. Example, PV-WAVE. Uncomment lines.
# Add other case statments for additional daemons.
#
PVI) # Use the daemonPath - arch binary already
ln -s $daemonPath /usr/tmp/$marker.vd$ndaemon
;;
#============================================================
*) # daemons you forgot
ndaemon=`expr $ndaemon - 1`
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo ''
echo 'Sorry! Skipped following DAEMON line. Fix $MATLAB/etc/lmboot script.'
echo ''
echo "$line"
echo ''
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
continue
;;
esac
echo "$line" | sed "s%$daemonPath%/usr/tmp/$marker.vd$ndaemon%"
>> /usr/tmp/$marker.dat
else
echo "$line" >> /usr/tmp/$marker.dat
fi
done) < $licensefile
MATLAB
TOOLBOX
When installed as described by the installation document, the logical names are defined on a system-wide basis at boot time through the execution of MATLAB:[ETC]MATLAB_SYSTARTUP.COM from SYS$MANAGER:SYSTARTUP_V5.COM. (See installation guide steps 8)
Symbols used to invoke MATLAB and its utilities, such as CMEX, are defined on a per-process basis through the execution of MATLAB:[ETC]MATLAB_SYLOGIN.COM from SYS$MANAGER:SYLOGIN.COM at login time. (See Installation Guide step 9)
If you want to maintain a MATLAB v3.5 environment and have the ability to run MATLAB v4.x, omit steps 8 and 9 of the installation procedure. Instead, following completion of the installation procedure, perform the following steps using the editor of your choice:
Copy the lines from MATLAB_SYSTARTUP.COM which define the logical names MATLAB and TOOLBOX to MATLAB_SYLOGIN.COM. The lines in MATLAB_SYSTARTUP.COM look like this:
$ DEFINE/SYSTEM/EXEC/TRANS=CONCEALED MATLAB DISK$USER:[MATLAB.]
$ DEFINE/SYSTEM/EXEC/TRANS=CONCEALED TOOLBOX DISK$USER:[MATLAB.TOOLBOX.]
Place these lines so they are the first commands to executed by the file.
From these lines remove the "/SYSTEM" qualifier, so they look like this:
$ DEFINE/EXEC/TRANS=CONCEALED MATLAB DISK$USER:[MATLAB.]
$ DEFINE/EXEC/TRANS=CONCEALED TOOLBOX DISK$USER:[MATLAB.TOOLBOX.]
Save MATLAB_SYLOGIN.COM and exit. (Do not save MATLAB_SYSTARTUP.COM.)
Now to setup the environment to run V4.x simply type: @DISK$USER:[MATLAB.ETC]MATLAB_SYLOGIN
Check whether the license daemons are running. Do a ps as indicated in the troubleshooting section of the Installation Guide.
If the license daemons are not running, you should execute lstmart. With a CPU-locked Multi-User license, however, the license daemons do not need to be run, so you should try starting MATLAB and let us know if you're getting any errors.
Check that the DAEMON line in the license.dat file is pointing to the correct location for lm_matlab.
Make sure the host name on the SERVER line in the license.dat file is correct.
Make sure the the UNIX ping <hostname> command returns <hostname> is alive where hostname is the name of the MATLAB server machine. If the ping command returns the error, <hostname> is not responding, then there is a problem with your network configuration such that connection to that machine will fail. Connection to the license daemons will, therefore, also fail.
Make sure that the network software TCPIP is running on your machine. Even for stand-alone machines, the license manager requires TCPIP.
It may be a typographical error in the feature line indicated by the error. For example, this error will occur if Signal_Toolbox is entered as signal_toolbox. Check the error message for typographical errors and case sensitivity in the name of the feature. Make sure the FEATURE line matches the passcodes as generated by The MathWorks, Inc.
The user is running the matlab executable in, say, $MATLAB/bin/sun4, rather than the matlab script in $MATLAB/bin. Note that sun4 can be replaced with any architecture we support, like RS/6000.
You may have the wrong matlab on the UNIX path or you may need to rerun install_matlab to set up the correct paths.
You do not have TCPIP software on your machine. To check, execute the UNIX ping command. e.g., ping <hostname> where hostname is the name of the machine from which you're trying to run MATLAB. If ping is successful, see (2) below.
You probably do not have 1700 at the end of the SERVER line in the license.dat file.
You probably installed the latest version of MATLAB (which uses FLEX 2.4c) without shutting the old (v2.21) license daemons.
This error indicates that you are running a version of FLEXlm older than 2.4c. You need to execute lmstart in V4.1 of MATLAB which executes the lmgrd and lm_matlab license daemons which ship with MATLAB 4.1.
You probably received new codes and did not restart the license manager. You can also try doing an lmreread.
Make sure you do not have a typographical error in the FEATURE line spelling.
The problem occurs with the logical LM_LICENSE_FILE set to NODE:FILE_SPEC.
MATLAB compiled with the VAX C compiler does not support accessing a license file through DECNET. This is because access to the license file is checked with a C standard runtime library routine called access. The VAX C runtime library access routine explicitly does not support access to a file through DECNET.
LM_LICENSE_FILE must point to a local license.dat file. This license.dat can be a VAX CLUSTER file, which is the equivalent of NFS mounting under UNIX.
If you are working on a Macintosh or a PC, you can print from the File menu, just as you would print a figure.
The Function block can use only a limited number of functions (the list of these functions can be found by clicking on Help in the function block). This block uses C routines to perform the calculations and is therefore very fast.
function[sys,x0]=show(t,x,u,flag)
if abs(flag)==0,
hs1=figure('units','normal','pos',[.8 .8 .1 .2]);
hs2=uicontrol(hs1,'style',...
'edit','units','normal','pos',[0 0 1 1],
...'min',0,'max',100);
set(hs2,'string','DIG_SCOPE');
sys=[0 1 0 1 0 0];
x0= hs2;
elseif abs(flag)==2,
tempstr=get( x(1) , 'string' );
newstr=str2mat( num2str(u),tempstr );
% Keep the last 50 values
[m n]=size(newstr);
if m>50,
newstr=newstr(1:50,:);
end
set( x(1) , 'string', newstr);
sys= x(1);
else
sys=[];
end
There is a technical note, which contains a list of compilers along with many addresses and phone numbers for compiler companies. This technical note can be found in pub/tech-support/tech-notes/mxeng1.txt.
#include <stdio.h>
#include "engine.h"
main()
{
Engine * ep;
char * buffer;
double userdata[3];
int i;
for (i=0;i<3;i++)
{
printf("Enter element #%d: ",i+1);
scanf("%lf",&userdata[i]);
}
ep=engOpen("setenv DISPLAY puff:0; matlab");
if (ep==NULL)
{
fprintf(stderr,"Error opening MATLAB");
exit(-1);
}
if engPutFull(ep,"mystuff",1,3,userdata,NULL)
fprintf(stderr,"Error entering data into MATLAB");
buffer=mxCalloc(201,sizeof(char));
engOutputBuffer(ep,buffer,200);
if(engEvalString("hankel(mystuff)"))
fprintf(stderr,"Error using hankel");
else
printf("Hankel Matrix was \n%s\n",buffer);
mxFree(buffer);
engClose(ep);
}
% Design an elliptical lowpass filter with passband cutoff % frequency at 20% of the sampling frequency, and stopband % cutoff frequency at 40% of the sampling frequency. % Passband ripple to be no more than 3dB, and stopband % attenuation greater than 30dB:
% First, generate the specs. Note that the cutoff % frequencies are specified in terms of the Nyquist % Frequency, which is half the sampling
% frequency:
Rp=3; % passband ripple
Rs=30; % stopband attenuation
Wp=.2*2; % Passband cutoff. Multiply by two to convert to % fraction of Nyquist frequency
Ws=.4*2; % Stopband cutoff
% Next, determine minimum order:
[N,Wn]=ellipord(Wp, Ws, Rp, Rs);
% Finally, feed the output of ellipord to ellip to generate % the filter:
[b,a]=ellip(N, Rp, Rs, Wn);
frequency=[0 w_stop1rightedge w_passleftedge... w_passrightedge w_stop2leftedge 1];
magnitude=[0 0 1 1 0 0];
Note that frequency always starts with 0 (DC) and ends with 1 (Nyquist frequency). The command
plot(frequency,magnitude)
will give a rough plot of the desired frequency response.
The following example designs a 10th order Remez filter with a passband from DC to 20% of the sampling frequency, and a stopband from 30% to 50% of the stopband:
N=10; % order
F=[0 0.2 0.3 0.5]*2; % Multiply by two to convert to % fraction of Nyquist frequency
M=[1 1 0 0];
b=remez(10,F,M);
Fs=10000;
b=remez(11,[0 1],[0 10000*pi],'differentiator');
freqz(b,a)
For an FIR filter (where a equal 1), you can just specify b:
freqz(b)
t=0:.001:1;
y=sin(2*pi*t*10)+sin(2*pi*t*200);
[b,a]=remez(20,[0 50 100 500]/500,[1 1 0 0]); % lowpass filter design
yfiltered=filter(b,a,y);
plot(1:length(y),y,1:length(yfiltered),yfiltered)
Filtfilt takes the same inputs and outputs as filter, but performs the filtering operation in both the forward and reverse directions (that is, it is a noncausal filter). This effectively squares the magnitude of the filter, but cancels any phase offset introduced by the filter.
Analog filtering is not supported by the Signal Processing Toolbox. Instead, either SIMULINK or the lsim function from the Control System Toolbox must be used.
y=sin(2*pi*(0:0.001:1));
subplot(311)
plot(y)
subplot(312)
plot(ifft(fft(y))) % Note the Y-axis limits!
subplot(313)
plot(real(ifft(fft(y))))
t=0:.001:1;
y=sin(2*pi*t*200);
plot(angle(fft(y)));
Instead, you get a strange-looking curve. The explaination of this phenomenon is as follows: The signal y is the product of an infinitely long, pure sine wave with a rectangular (boxcar) window. The Fourier transform of the pure sine wave consists of 2 impulses (i.e. delta functions) at 200 Hz and -200 Hz. The Fourier transform of the boxcar window is a sinc functions. When you multiply these two in time, you are convolving them in frequency, so the result in the frequency domain is the sum of two shifted sinc functions, one at 200 Hz and the other at -200 Hz. Thus, there is some small spectral component of the signal even at frequencies other than the fundamental frequency (200 Hz), and it is this spectral content that causes the phase of the signal to look like it does.
1. The data is broken up into M sections, where M is user-specified.
2. The M sections are detrended, removing linear trends (including the DC
component).
3. The sections are windowed using a Hanning window.
4. The FFTs of the detrended, windowed sections are taken.
5. The magnitude of the FFTs are averaged together and normalized by the square of the norm of the Hanning window, to generate an asymptotically unbiased estimate.
An asymptotically unbiased estimate will have an expected value which approaches the true expected value of the underlying random signal as the number of samples used increases. The averaging in this process causes the variance of the PSD to be diminished by a factor of M. This lowers the floor of random noise in a signal, making it easier to pick out deterministic signals.
1. Use the psd and csd functions, instead. Calling either of these functions without an output argument will cause them to generate a power plot without confidence intervals.
2. Modify the output of spectrum to set the confidence ranges to NaN. The following are two examples, one for the case of one input to spectrum, and the other for the case of two inputs to spectrum:
One input case
x=rand(1024,1);
P=spectrum(x,128);
P(:,2)=nan*P(:,2);
specplot(P)
Two input case
x=rand(1024,1);
y=randn(1024,1);
P=spectrum(x,y,128);
P(:,6:7)=nan*P(:,6:7);
specplot(P)
Results may be inaccurate. RCOND = xxxxx
This error most often happens in two cases. The first is that part of the transfer function's magnitude is relatively flat (has slope close to zero). The second is that extremely high frequencies (greater than 100MHz) are being specified in the frequency vector.
Many times this warning can be ignored. It is best to inspect the designed filter to see how well it performs. The call to invfreqs in the following example will cause this warning message, but the example shows that the filter still fits the desired curve quite well:
clf;
w=linspace(0,100,1024);
H=1-0.1*(1-1./(1+(j*w).^0.3));
% generate desired frequency response
[b,a]=invfreqs(H,w,5,5);
% design filter with that response
[H1,w1]=freqs(b,a);
% generate freq. resp. of designed filter
plot(w1,abs(H1))
% plot freq. resp. of designed filter
set(gca,'xlim',[min(w) max(w)])
% adjust x-axis limits
hold on
% freeze plot
plot(w,abs(H),'r')
% plot freq. resp. of desired filter in red
hold off
% unfreeze plot
In those cases where one can't ignore the warning message, the following hints may help:
1. For transfer functions with regions of flat slope, sample the flat portion of the transfer function less finely than the non-flat portions. In the above example, you might try
w=[linspace(0,10,1020),linspace(11,100,4)];
This will sample the steeper portion of the transfer function from 0 to 10 Hz 1020 times, and only sample the flatter portion from 10 to 100 Hz only four times.
2. For extremely high frequencies, try scaling the problem down. Design a similarly-shaped filter in a lower frequency band, and then scale the final result up to the desired frequency using the lp2lp function.
>>[b,a]=cheby1(8,.05,.08);
The transfer function of this filter at DC (H(0)) is:
>>h=freqz(b,a,[0 0]);h=h(1)
h =
0.9943
Since the filtering is done with filtfilt, the transfer function is effectively squared, giving a true DC transfer function of
>>h*h
ans =
0.9886
So the DC component of the signal will be multiplied by 0.9886. One way to avoid this problem is to use decimate with an FIR filter, as demonstrated below:
xd=decimate(x,10,'FIR');
A useful property of the FIR filter in this case is that its DC gain is always 1, so it will not affect the DC offset of your data.
C(z) = A(z) * B(z)
where * denotes multiplication. To invert this process, i.e. to deconvolve A from C, would be equivalent to dividing both sides of the equation by A(z). Thus,
B(z) = C(z) / A(z)
It is well known that in the time domain, passing an impulse function through a filter yields the filter's impulse response. In the equation above, C(z)/A(z) can be viewed as just another filter. So to determine what b[n] is, all one needs to do is filter an impulse function by B(z)=C(z)/A(z). That is precisely what the deconv function does, via the command
q = filter(C, A, [1 zeros(1,nC-nA)]);
Unfortunately, if any of the roots of A(z) happen to fall outside of the unit circle, this results in an unstable filter, and this method breaks down.
A better method of deconvolution (but one which is far more computationally intensive) realizes that convolution is the equivalent to a matrix multiply in the form of Ax=b. This can be solved in MATLAB using the equation x=pinv(A)*b. For example:
x=[1 2 1]'; % make sure x and y are columns!!!
y=[1 2 3 4 5]';
z=conv(x,y); % now we will try to recover y
% convmtx generates the A matrix mentioned above
A=convmtx(x,length(z)-length(x)+1); %length(z)-length(x)+1==length(y)
y_recovered = pinv(A)*z
disp('norm of error = ')
norm(y_recovered-y)
Note that this method will break down in the presence of noise. If we simulate random noise being added to z by adding the line
z=z+[.9 .2 .4 .1 .31 .78 .21]';
Then the norm of the error rises to 0.8683 from 8.8596e-15. It can be shown that this form of deconvolution amplifies noise proportionally to the inverse of the singular values of A. In this case, the singular values of A are
>>svd(A)
ans =
3.7562
3.0873
2.1631
1.2120
0.4605
By inspection, we can see that one singular value is significantly closer to zero than the rest (which, when inverted, will amplify the noise in this system more than the rest). By specifying tolerance, an optional second argument to pinv, we can eliminate the effect of the smallest singular value:
y_recovered = pinv(A,0.5)*z
In this case, 0.5 was chosen because it is greater than the smallest singular value, but smaller than the rest. The norm of the error now drops back down to 0.4810, a decrease of almost 50%. Unfortunately, there are no clear cut rules to performing this sort of analysis, and only experience can help to determine which singular values should be kept and which should be thrown out.
The following M-file demonstrates how to use xcorr to determine how much offset exists between two signals, x1 and x2:
t=0:.01:1.01;
x1=[t.^2]; % generate sample data
x2=[0 0 0 t.^2];
% x2 is delayed version of x1, delayed by 4 samples
xc=xcorr(x1,x2); % perform cross correlation
index=find(xc==max(xc));
% this is the index of the cross correlation where
% the cross correlation is at its maximum. I.e.
% this is where x1 and x2 line up the best.
middle=(length(xc)+1)/2;
% this is the middle element (since length(xc) is always % odd)
if index-middle>=0,
disp(['x2 is delayed from x1 by ' num2str(index-middle)...
' sample(s)']);
else
disp(['x1 is delayed from x2 by ' num2str(middle-index)...
' sample(s)']);
end