Common Problems with Matlab

Sometimes Matlab does not give you the result which you would expect. There are some peculiarities you have to be aware of.

General

How can I see more than 5 digits of my results?
Matlab does all computations with 15 digits accuracy, but shows only 5 to keep the output more compact. Also, in vectors and matrices Matlab uses a common factor 10m for all elements. If matrix elements have very different sizes, small elements will be displayed as 0.0000. Use format long g to see all computed digits, and to get scientific notation for each matrix element.
When I use ``e^x'' or ``ln(x)'' I get strange results or errors
The exponential function must always be written as exp(x), not e^x. The logarithm function must be written as log(x), not ln(x). (For some reason dsolve does accept ln(x).)
fzero('exp(-t)-t',1) gives an error (same for fsolve)
The variable must be called x: use fzero('exp(-x)-x',1). Alternatively, you can use an inline function: g=inline('exp(-t)-t','t'); fzero(g,1)
solve gives warning like ``1 equations in 3 variables'' and does not give correct answer
If you use a command like solve(F,G,x,y) and if F or G happens to be x or y, Matlab does not recognize it as an equation. You can work around this design flaw by using a command like solve(2*F,G,x,y).

Graphs

How can I zoom in on a certain part of my graph?
Use axis([xmin xmax ymin ymax]) after your plot commands. Use axis tight if you want to see everything you plotted.
ezplot does not show all of my plot
ezplot tries to select the y-range in such a way that you only see the interesting part of your functions. Try using axis tight or axis([xmin xmax ymin ymax]) after the ezplot command.
How can I label a graph?
Use the title, xlabel, ylabel, legend commands, e.g.
x=0:.1:10; y1=sin(x); y2=cos(x);
plot(x,y1,'-',x,y2,'--')
title('Trigonometric functions')
xlabel('x')
ylabel('y')
legend('sin(x)','cos(x)')
My graph does not fill the whole page.
By default the paper is vertically oriented (``portrait''), and the plot is in a rectangle which is wider than high (ratio 4:3), so that there is a lot of empty space on the page. To obtain a larger plot with the page in horizontal orientation (``landscape''), use
orient landscape
print test1.ps    % save plot in file test1.ps
How can I put several graphs on one page?
Here is an example which puts one graph in the top half and one graph in the bottom half of the page:
subplot(2,1,1)    % divide page in 2 rows, 1 col, use 1st part
ezplot('sin(x)',[-3 3])  % plot command for first graph
subplot(2,1,2)    % use 2nd part of divided page
ezplot('x^2', [-3 3])    % plot command for second graph
orient tall       % make plot tall enough to fit whole page
print test1.ps    % save plot in file test1.ps
How can I change the plot style and color in ezplot ?
First save the file setcurve.m in your home directory.

To change the curve color to red, use the following command after the ezplot command:

setcurve('color','red')

To change the curve color to green, use a dashed instead of a solid line, and make the lines thicker, use the following command after the ezplot command:

setcurve('color','green','linestyle','--','linewidth',2)

(Type help plot to see available line styles and colors.)

m-files

I saved my commands in the file prob1.m, but when I type prob1 Matlab says it is undefined
You must tell Matlab where it should look for m-files. There are several ways to do that:

In the Matlab desktop window you can use the current folder field in the desktop toolbar (click on "..." to the right of the field), see Matlab desktop window with current folder field

If you are on a Windows machine you might save your m-file in the directory C:\My Documents\homework . At the Matlab command prompt you can type addpath('C:\My Documents\homework') .
On the WAM or Glue system you should use addpath('H:\mydocuments\homework').

In the Matlab desktop window you can also select in the "File" menu the item "Set Path...". Then use "Add Folder...", select a folder and hit "OK". Then click "Save", so that you do not have to do this again the next time you start Matlab.

If you are on a Unix machine you might save your m-file in the directory /homes/myname/homework1 . At the Matlab command prompt ">>" you should type addpath('/homes/myname/homework1') .

How can I output numerical results together with describing text?
For scalar values use fprintf with %g for each value you want to insert in the text, e.g.,
fprintf('The volume is %g, the area is %g\n',volume,area)
If you want to see e.g. 15 digits use %.15g instead of %g in fprintf.
For vectors and matrices use disp, e.g.,
x = sqrt(1:6);
disp('The square roots are'); disp(x)
When I use echo on and my m-file contains for ... end the commands in the loop get echoed many times
Replace ``end'' with ``echo off; end; echo on'' to supress echoing after the first loop iteration.
I generate several plots in my m-file. When I run the m-file I only see the last plot. The same thing happens when I publish an m-file with several plot commands in one cell.
Method 1: put a pause statement after each plot command. Then Matlab will wait for you to press a key before moving on.

Method 2: put the statement figure before each plot command. This will generate a separate window for each plot, and show all plots with publish.

I use hold on with several plot commands in my m-file. I want to see what the graph looks like after each plotting command, but Matlab waits until the last plotting command before showing the graph.
Put a drawnow after each plotting command. This forces Matlab to update the graph immediately, rather than waiting until the end of the m-file.

Differential equations

When I try to use dirfield, vectfield or vectfieldn, Matlab says the command is undefined
The commands dirfield, vectfield, vectfieldn are not built in. You must save the files dirfield.m, vectfield.m, vectfieldn.m into your home directory by clicking on these links and then selecting the ``Save As...'' command in your browser. If you started Matlab from your home directory the command dirfield will be available. If you started Matlab from some other directory Matlab might not find dirfield. In this case you can use the cd or addpath command in Matlab to fix the problem.
Inline functions give strange results with dirfield, ezplot, fplot or other commands
The inline function must use ``.*'', ``./'', ``.^'' instead of ``*'', ``/'', ``^''. Double-check this. The function for dirfield must be defined as a function of two arguments, even if it does not depend on t or y.
dsolve returns an expression with RootOf. Whatever I do with this answer I get an error.
This is a bug in Matlab. You can interpret the output as an implicit function, with ``y'' substituted for ``_Z'' (example). But if you want to do anything with the answer, like substituting values or using contour, you must type in the function with ``y'' substituted for ``_Z'' yourself.
Matlab cannot solve a simple initial value problem like dsolve('Dy=y^2','y(0)=0','t').
This is a bug in Matlab. For a separable equation y'=f(t)g(y) Matlab often fails to find the solutions of the form y=a where a is a solution of g(a)=0.
dsolve gives error message ``Index exceeds matrix dimension''.
This is a bug in Matlab which may happen if you have Dy on the right hand side, e.g., dsolve('y/x=Dy','x'). Try putting Dy on the left hand side of the equation.
Matlab's solution looks different from what I would expect
Sometimes Matlab finds the correct solution, but writes it in a strange way. Try using s=simplify(sol) and s=simple(sol) to rewrite the solution. E.g., for sol=dsolve('Dy=y+sin(10*t)','t') using s=simple(sol) helps.
When I use dsolve in a for loop, Matlab does not use the value of the loop variable
The arguments of dsolve are strings which are not evaluated using the current values of the variables. Often it is possible to use dsolve outside of the loop with a symbolic parameter, and then to substitute values in the resulting symbolic expression inside the loop (Example).

If you really need to put dsolve inside the loop, you must convert the value of the loop variable to a string using num2str and concatenate strings using [string1,string2]. E.g., to solve y' - a y = 1 for a=-2,-1,...,2 you must use

for a=-2:2
  dsolve(['Dy-(',num2str(a),')*y=1'],'t')
end

Note that you cannot put dsolve outside of the loop in this case (why?).

Laplace transforms

When I enter a symbolic expression using Heaviside or Dirac I get an error
This is a bug. When you define an expression using Heaviside or Dirac you must use it in a string (inside quotes), e.g., f='2*Heaviside(t-2)+3'; laplace(f,t,s)
When I use ezplot with a function containing Heaviside I get an error.
This is a bug. A fix is to put the file Heaviside.m in your home directory.

MATH 246 course page

Tobias von Petersdorff , tvp@math.umd.edu