School of Mathematics
Mathematics Help Centre
The Matlab Tips Page
The Matlab Tips Page
Welcome to the Matlab Tips Page. The purpose of this page is to provide students with some tips and ideas for using Matlab. Bookmark this page and watch it grow as time goes on.
Tip |
Use |
Allows user to enter data from keyboard. |
|
Constructing matrices and abstracting information from them. |
|
Tips on M files |
|
Avoid wrinkles in plot and ezplot |
|
format output for looks and functionality |
|
|
Frequently a user needs to enter data from the keyboard. This can be many forms, but most commonly a number is entered, either a real or an integer. The statement below asks for such input. Note that a variable is needed to hold the data.
m = input('Number of cosine terms in Fourier series? ');
This will place an integer or real value into m, according to the users response.
A character or string can be entered as long as it is enclosed by quote marks, eg an appropriate response to
m = input('What is your name? ');
could well be 'Igor'.
Working With Matrices
Frequently you need to build a matrix out of several different components. When this is so, it helps to set aside memory before constructing the matrix. If not, memory will be allocated as it is needed, which is substantially slower. Depending on the structure of the matrix, I use either the ones function or the zeros function, eg A = ones(m,n); and B = zeros(2,m) will set up matrices full of ones and zeros respectively. If you do not supply both the number of rows and columns then Matlab will assume a square matrix is required, eg ones(3) sets up a 3x3 matrix full of 1's.
Once this is done, a matrix can be constructed using semicolons. Try the following code in Matlab to see its effect. The semicolons have been left off the end of each line.
x = 1:10
A = ones(length(x),2)
y = sin(x)
A(:,2) = y'
It is very important to match up the dimensions of your matrices and columns and / or rows. The statement A(:,2) = y fails because y is a row vector and A(:,2) is a column of A.
It is often handy to make a vector equal to a row or column of a matrix. After the above commands have been tried, try the following.
c1 = A(:,1)
c2 = A(:,2)
Function M files can be tricky things to work with. One matter to bear in mind is that your M file may have to work with both scalars and vectors. If you write an M file to calculate some function f(x) where x is a scalar, some user may wish to plot the graph of f(x) and send a vector of x values to your M file. If the function is not defined with vectors and scalars in mind, it may crash and burn. Consider the following M files as an example.
function y = f1(x);
y = x^2;
function y = f2(x);
y = x.^2;
The second function will work with both scalars and vectors, whereas the first only works with scalars.
If the definition of the function depends on the value of x, the problem becomes even more acute. For example, consider the function f(x) which takes the value of √ x if x≥ 0 and -√ (-x) if x<0. We need to define the function using an if statement, and need to test to see if x is > 0. Try the following.
function y = f3(x);
if x >= 0
y = sqrt(x);
else
y = -sqrt(-x);
end;
Test this M file on a scalar, say f3(4) or f3(-9). Now, create an x vector, say x = -3:0.01:3 and try to graph f3(x) against x using a plot command. Try also a vector x = 0:0.01:4. Then try the following M file on both, as well as on scalars.
function y = f4(x);
y = zeros(1,length(x));
for i = 1:length(x)
if x(i) >= 0
y(i) = sqrt(x(i));
else
y(i) = -sqrt(-x(i));
end;
end;
Note that the function length(x) returns the number of elements of x.
In some of the Matlab tests in first year you are asked to use Matlab to find the limit of a function to, say, three decimal places. If the function has obscure behaviour, you cannot simply calculate the function at the appropriate x value. So the solution is to graph the function using either plot or ezplot. However this can be a little trickier than it sounds. For example, try to find the limit of the function f(x) = (x2 - 0.25)*tan(p x) as x approaches 0.5.
The commands below will plot the graph and allow you to zoom in to try to estimate the limit. However, you will quickly find that the graph simply isn't accurate enough to estimate the limit to the required precision.
EDU>> x = 0.4:0.01:0.6;
EDU>> y = (x.^2 - 0.25).*tan(x*pi);
EDU>> plot(x,y)
EDU>> zoom on
The way around this to to redefine x and then repeat the other commands, using something along the lines of :
EDU>> x = 0.45:0.001:0.55;
Similar problems can occur using ezplot. It appears that ezplot creates a vector of x and y values itself and sends them off to be plotted. So if you zoom in too closely in ezplot, you will find yourself running out of precision again. The trick is simply to decrease the domain over which you want the function plotted, while keepign the same number of points.
The use of Matlab in your assignments usually relates to investigating some mathematical question. It is not enough to ask Matlab to calculate something, you must then view the results of that calculation. Your life will be made easier if you organise your programs to output your results in some way that will make them easy to view. The following example puts together some function M-files and a programme M-file to answer a simple question.
Suppose you are asked to determine the relationship between the integer sum 1+2+3+...+n and the quadratic polynomial n*(n+1). A good start would be to write two function M-files that would calculate the two results and a programme M-file that would compare the two side by side. Hopefully some relationship would show up.
Copy the two M-files below and test them for several values of n. (Also test your function M-files against some value for which the answer is known.)
function y = nsum(m );
% M-file to find 1+2+3+...+m to compare with m*(m+1)
sum = 0;
for i = 1:m
sum = sum+i;
end;
y = sum;
function y = quadratic(m );
% M-file to find m*(m+1), to compare with 1+2+3+...+m
y = m*(m+1);
After testing these M-files on several values such as 2, 3 or 4, try the following programme M-file.
% programme M-file to compare 1+2+3+...+n with n*(n+1)
fprintf('This programme compares 1+2+3+...+n with n*(n+1)\n');
% or use disp('This programme compares 1+2+3+...+n with n*(n+1)');
maxn = input('Enter maximum value you wish to test >');
fprintf('\n\n');
fprintf('Sum Quadratic\n-------+--------\n');
for = 1:maxn
fprintf('%5.0f%10.0f\n',nsum(n ),quadratic(n ));
end;
After running this test program,you will easily see that the quadratic is twice the sum. After discussing the output statements using fprintf, we will extend the programme to check a little further.
The fprintf statement always seems to have a string enclosed in single quotes inside it. This string not only gives any text to be printed out, it also has format specifiers in it, which are prefixed by a \ or a %. Different specifiers have different meanings. For example the specifier \n means start a new line. Try the statements below in the command window.
fprintf('Move like water, strike like thunder.');
fprintf('Not another cliche.\n');
Now suppose you want to print out a real number, say one held in the variable x. You want it to be displayed in a space 10 characters wide with 4 decimal places. Try this (after letting x have a value!).
fprintf('%10.5f',x)
The format specifier says that 10 spaces will be required and 5 of them come after the decimal place. The f means that a floating point number is being printed, and x appears outside the quotes to tell it what variable is being printed. Remember that all your format specifiers must appear inside quote marks.
Experiment with the above programme to increase or decrease the number of decimal places. Also, add code asking it to calculate and print the ratio of the quadratic and the sum, ie something like quadratic(n)/nsum(n). Can you change the statement printing out the text to include a heading for the ratio as well?
It is worth noting that the format specifier for strings is \ms, where m is the number of spaces allocated for printing the string. So for example, to read in and print out a name, you might try the following.
name = input('What is your name, master? ');
fprintf('I am the slave of %10s\n',name);
Sometimes you need to write a programme that calls a function of a function, and you want the user to be able to change functions at their discretion. For example a function to perform numerical integration using Simpson's method prompt the user for input of the interval to be integrated across, and the name of a function they want integrated. Your programme would then, if it is well designed, call a function that performed the integration and returned the value to the programme, which would then return the answer to the user. However you would like the user to be able to integrate different functions as easily as possible.
The solution to this is to allow the function called by the programme you write to accept the name of another function as a parameter. In other words, the function called by your main programme should have a calling syntax like this : MyFunc(Func,x). Func would be a string, assigned along the lines of Func = 'Func1', or using an input statement as suggested earlier in these notes.
The function whose name is given by the user can be evaluated with a statement like y = feval(Func,2) or feval(Func,x)
Now, how do we call a function of a function? Try the following two M-files.
function y = f1(x);
y = x*x;
function y = f2(Func, x);
% Use feval to evaluate second function
y = 2*feval(Func, x);
In other words, whatever function f1 is, f2 calculates that function and then doubles it. Create these two M-files and save them to your floppy disk. Now try the following commands.
Func = 'f1';
x = 2;
z = f2(Func,x)
You will find that the command successfully evaluates twice x^2 for various values of x. Note that the approach here is different to that in the demos and manual. However I could not get that approach to work, so resorted to using feval as above.