Saving your Matlab sessions

March 26th, 2010 No Comments   Posted in Examples

Often one wants to save the data or variables to another occasion. Maybe one wants to save the whole Matlab session. This can be done. Commands are put in a m-file but data or variables are stored in a mat-file (binary file) which can be opened with Workspace Browser. First have a look in the workspace to find out how your varables look like. Then save these in a mat-file.

1
2
3
save execution1 % variables will now saved in a mat-file execution1.mat
clear % clears all variables from the present Workspace.
load execution1 % restores all variables stored in the execution1.mat

We can also store everything that is displayed in the command window. Like the whole session both the command lines and the output from Matlab, id est the calculations. This can be done by:

1
diary exercise % stores the whole session in file exercise(ascii-file)

Everything that follows from now on in the command window will be stored in the ascii-file exercise. Write just anything to get some response from Matlab into the command window. diary off % turns of the storage of the session to the file exercise9. Find the file exercise and see if the content in the file is the same that were displayed in the command window!

Matlab Quick Search:

  • matlab command window
  • matlab print matrix to command window
  • can i diary a xml file in MATLAb
  • open command window in matlab
  • matlab solve integral in command window
  • matlab set path for session
  • matlab save command window to file
  • matlab diary with date
  • matlab diary tutorial
  • purpose of matlab command window

Analysis of Functions, Interpolation, Curve Fitting, Integrals and Differential Equations 2

March 23rd, 2010 No Comments   Posted in Documents

Localize minima and maxima of functions

Let us try to find the local minima and maxima for the function func(x). The interval of interest is [-6 0]. The algorithms are iterative. There are 2 methods to use. The first one decides x in a given interval, and the second one looks for x around an initial guess. To decide the maxima we are looking for an x that minimizes the negative function: -func(x).

fminbnd(func,x1,x2): Gives the x-value for a local minima.

1
[x,y,flag,info]=fminbnd(func,x1,x2)

As above, but we also get the y-value. Flag gives a positive number, if minima is localized and a negative number otherwise. We store the information about the iterations in the variable info.
fminsearch(func, x0,): Gives the x-value for a local minima somewhere close to the initial guess x0.
Decide the global minima and maxima that exist on the interval -8 to 0 for the function func(x). This gives:

1
2
3
4
5
6
x =
-1.7326
y =
-5.9511
flag =
1

This seems to be true for our function. If we want to find the maxima values, the same command can be used. The only difference will be a minus sign in front of the function. Whenever we call the function fzero. The command looks for a minima but will in fact localize the maxima due to the minus sign. See below!

1
2
3
function f=func(x)
f=-(3*sin(x)-2+cos(x.^2)); % Note the minus sign in front of parenthesis.
>> fminbnd(@func,-8,0)

Look below for the answer. Note that the y-value is negated. Compare the plot func(x to our result below.

1
2
x = y =
-1.8691 -5.0046

Our maxima occurs at x=-1.8691, and the value of y becomes y=5.0046. Is this an accurate result according to your opinion?

Interpolation of data sets

Assume that we have made a number of measurements and thereby guessed a function relating the input and output. Then we also have some knowledge of the values between the measured points. This is very common in sampled applications. Think of a sampled continuous sine wave function with a very low sampling frequency. This can be done very simply, if we use a vector x with low resolution. Let us create one. Use the x vector values and calculate the corresponding sine function values and plot it in bellow Figure.

1
2
x=0:20;
y=sin(x), plot(x,y),grid



Low resolution sine plot

We could think of it as a rather badly shaped sine wave curve probably due to a too long sampling period. By interpolation one decides on a function P(x) that passes through certain known data points. The interpolated function can be used to calculate the function value approximately for any x. Normally one uses polynomials or functions combined from polynomials (spline functions) to make interpolations, but also sine and cosine waves can be useful.
Now, let us see what happens when we try to make a curve fit 10 random numbers.

1
2
y=rand(1,10) % 10 random numbers in a row vector
plot(y,'*')

See the figure below. Investigate whether it is possible to find a polynomial that can be adjusted to the random data.
Enter the figure window under Tools-> Basic Fitting. Mark the ninth-degree polynomial. This gives a polynomial that passes through all random data points. The basic fitting uses the least square method. Even if we use a lower degree it is still the best solution according to the least square method.

Mark the small box show equation. We can then explicitly see the polynomial in the figure window. Remove the ninth-degree polynomial and choose a linear equation instead. Matlab will now try to find the best linear equation. Mark the small box plot residuals. The error residual between each data point and the linear equation is calculated and shown. Despite large discrepancies this is the best first-order polynomial.

The error residual between each data point and the linear equation

We will now try to accomplish the same thing with Matlab commands that we did with the interactive basic fitting in the figure window.

1
2
3
4
5
6
7
8
9
10
11
y=rand(1,10), x=1:10;
plot(x,y,'*') ,hold on
p1=polyfit(x,y,1) % Best coefficients for a first order polynomial
% according to the least square method. Stored in
% a ector p1.
p9=polyfit(x,y,9) % Ninth-order coefficients.
xx=1:0.01:10; % Improves the resolution in the x-vector.
p1_func=polyval(p1,xx);% Calculates polynomial values for x-values.
p9_func=polyval(p9,xx);% As above.
plot(xx,p1_func,xx,'',p9_func,'-.')
legend('y=randn(1,10)','linear','9th degree')

The result of the commands can be seen in the figure below. The higher the order of the polynomial, the higher the oscillation between the data points. Notice the huge peaks between values 1 and 2 and 9 and 10. You should have been alarmed if this had been real data and your mission was to find an interpolation function that nicely fits the measurements. It is definitely not common sense to look for a ninth-order polynomial for a data set of 10 points.

The higher the order of the polynomial, the higher the oscillation between the data points

Integrals

Matlab can solve integrals and differential equations with numerical methods. Later on in this course we will show how integrals and differential equations can be solved in Symbolic Math toolbox. Numerical integration in Matlab is performed by the command quad. This stands for numerical quadrature. We can solve integrals only with defined limits. This can be done for single, double and triple integrals. To solve generalized integrals or integrals expressed with symbols, we must use the Symbolic Math toolbox. Let us exemplify with some numerical examples.

Example 1: Single integrals

Decide the integral below.

First we put the integrand in a function file: integrand.m.

1
2
function y=integrand(x)
y=sqrt(exp(x));

Write!

1
I1=quad('integrand',0,10)

Matlab gives:

1
I1 = 294.8263

It seems reasonable enough, if we plot the function. We can also use quad with a fourth argument, namely the tolerance for the calculation. This decides when the numerical integration will stop. The two following examples can be hard to understand, if one lacks the background of multivariable calculus.

Example 2: Double integrals

Calculate the double integral below.

Make as in the previous example a functionwhere we put the primitive function. We name the m-file as integrand2.m

1
2
function z=integrand2(x,y)
z=sqrt(exp(x)).*sqrt(exp(y));

Let us now call the function dblquad instead of it.

1
I2=dblquad('Integrand2',0,1,0,1)

and the answer is:

1
I2=1.6834

We will now take a look of the integrated area.

1
2
3
4
[X,Y]=meshgrid(0:0.1:1,0:0.1:1); % Makes a grid of calculation points.
Z=Integrand2(X,Y); % Calculates the integral.
mesh(X,Y,Z) ; % Makes a plot that connects these points.
% punkter.

The last three lines achieves Figure below.

Double integral

Matlab can also perform triple integrals. This example can be found by help triplequad.

Example 3: Triple integrals

A function f = y*sin(x)+z*cos(x) is integrated for the intervals 0 < x < pi, 0 < y < 1 and -1 < z < 1. This is achieved by:
First we create a function file integrnd.m.

1
2
function f = integrnd(x,y,z) % 3 input arguments and 1 output argument.
f = y*sin(x)+z*cos(x);

We refer to this m-file by using its handle. In the matlab command window we simply write:

1
triplequad(@integrnd,0,pi,0,1,-1,1);

Matlab Quick Search:

  • MATLAB Differential Equations Tutorial
  • randn matlab
  • rand(2 3 4) matlab
  • matlab tutorial to find QAM of SINEWAVE
  • rand function in matlab
  • rand randn matlab unterschied
  • applications of interpolation and curve fitting matlab tutorial
  • simple rand matlab tutorial
  • what does rem mean in matlab?
  • matlab tutorial integral

Controlling Command Window Input and Output

March 19th, 2010 No Comments   Posted in Documents

The format Function

The format function controls the numeric format of the values displayed. The function affects only how numbers are displayed, not how MATLAB software computes or saves them. Here are the different formats, together with the resulting output produced from a vector x with components of different magnitudes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
x = [4/3 1.2345e-6]
 
format short
 
   1.3333    0.0000
 
format short e
 
   1.3333e+000  1.2345e-006
 
format short g
 
   1.3333  1.2345e-006
 
format long
 
   1.33333333333333   0.00000123450000
 
format long e
 
   1.333333333333333e+000    1.234500000000000e-006
 
format long g
 
   1.33333333333333               1.2345e-006
 
format bank
 
   1.33          0.00
 
format rat
 
   4/3          1/810045
 
format hex
 
   3ff5555555555555   3eb4b6231abfd271

If the largest element of a matrix is larger than 103 or smaller than 10-3, MATLAB applies a common scale factor for the short and long formats.
In addition to the format functions shown above

1
format compact

suppresses many of the blank lines that appear in the output. This lets you view more information on a screen or window. If you want more control over the output format, use the sprintf and fprintf functions.

Suppressing Output

If you simply type a statement and press Return or Enter, MATLAB automatically displays the results on screen. However, if you end the line with a semicolon, MATLAB performs the computation but does not display any output. This is particularly useful when you generate large matrices. For example,

A = magic(100);

Entering Long Statements

If a statement does not fit on one line, use an ellipsis (three periods), …, followed by Return or Enter to indicate that the statement continues on the next line. For example,

s = 1 -1/2 + 1/3 -1/4 + 1/5 – 1/6 + 1/7 …
– 1/8 + 1/9 – 1/10 + 1/11 – 1/12;
Blank spaces around the =, +, and – signs are optional, but they improve readability.

Command Line Editing

Various arrow and control keys on your keyboard allow you to recall, edit, and reuse statements you have typed earlier. For example, suppose you mistakenly enter

1
rho = (1 + sqt(5))/2

You have misspelled sqrt. MATLAB responds with
Undefined function or variable ‘sqt’.
Instead of retyping the entire line, simply press the up key. The statement you typed is redisplayed. Use the left key to move the cursor over and insert the missing r. Repeated use of the up key recalls earlier lines. Typing a few characters and then the up key finds a previous line that begins with those characters. You can also copy previously executed statements from the Command History. For more information, see Command History

Matlab Quick Search:

  • fprintf matlab
  • matlab controls tutorials
  • matlab fprintf longEng
  • tutorial matlab fprintf

Manipulating Matrices

March 13th, 2008 No Comments   Posted in Documents

Matrices and Magic Squares

Matlab MatrisIn MATLAB, a matrix is a rectangular array of numbers. Special meaning is sometimes attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or column, which are vectors. MATLAB has other ways of storing both numeric and nonnumeric data, but in the beginning, it is usually best to think of everything as a matrix. The operations in MATLAB are designed to be as natural as possible. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily. A good example matrix, used throughout this book, appears in the Renaissance engraving Melancholia I by the German artist and amateur mathematician Albrecht Dürer.

Matrices and Magic Squares

This image is filled with mathematical symbolism, and if you look carefully, you will see a matrix in the upper right corner. This matrix is known as a magic square and was believed by many in Dürer’s time to have genuinely magical properties. It does turn out to have some fascinating characteristics worth exploring.

Entering Matrices

The best way for you to get started with MATLAB is to learn how to handle matrices. Start MATLAB and follow along with each example.You can enter matrices into MATLAB in several different ways:

  • Enter an explicit list of elements.
  • Load matrices from external data files.
  • Generate matrices using built-in functions.
  • Create matrices with your own functions in M-files.

Start by entering Dürer’s matrix as a list of its elements. You have only to follow a few basic conventions:

  • Separate the elements of a row with blanks or commas.
  • Use a semicolon, ; , to indicate the end of each row.
  • Surround the entire list of elements with square brackets, [ ].

To enter Dürer’s matrix, simply type in the Command Window

1
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

MATLAB displays the matrix you just entered.

1
2
3
4
5
A =
16  3  2  13
5  10  11  8
9  6  7  12
4  15  14  1

This exactly matches the numbers in the engraving. Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can refer to it simply as A. Now that you have A in the workspace, take a look at what makes it so interesting. Why is it magic?

sum, transpose, and diag

You’re probably already aware that the special properties of a magic square have to do with the various ways of summing its elements. If you take the sum along any row or column, or along either of the two main diagonals, you will always get the same number. Let’s verify that using MATLAB. The first statement to try is

1
sum(A)

MATLAB replies with

1
2
ans =
34 34 34 34

When you don’t specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of a calculation. You have computed a row vector containing the sums of the columns of A. Sure enough, each of the columns has the same sum, the magic sum, 34.

How about the row sums? MATLAB has a preference for working with the columns of a matrix, so the easiest way to get the row sums is to transpose the matrix, compute the column sums of the transpose, and then transpose the result. The transpose operation is denoted by an apostrophe or single quote, ‘.
It flips a matrix about its main diagonal and it turns a row vector into a column vector. So

1
A’

produces

1
2
3
4
5
6
7
ans =
 
A =
16  5  9  4
3  10  6  15
2  11  7  14
13  8  12  1

And

1
sum(A’)

produces a column vector containing the row sums

1
2
3
4
5
ans =
34
34
34
34

The sum of the elements on the main diagonal is easily obtained with the help of the diag function, which picks off that diagonal.

1
diag(A)

produces

1
2
3
4
5
ans =
16
10
7
1

and

1
sum(diag(A))

produces

1
2
ans =
34

The other diagonal, the so-called antidiagonal, is not so important mathematically, so MATLAB does not have a ready-made function for it. But a function originally intended for use in graphics, fliplr, flips a matrix from left to right.

1
2
3
4
sum(diag(fliplr(A)))
 
ans =
34

You have verified that the matrix in Dürer’s engraving is indeed a magic square and, in the process, have sampled a few MATLAB matrix operations. The following sections continue to use this matrix to illustrate additional MATLAB capabilities.{mospagebreak}

Subscripts

The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the fourth row and second column. For our magic square, A(4,2) is 15. So it is possible to compute the sum of the elements in the fourth column of A by typing

1
A(1,4) + A(2,4) + A(3,4) + A(4,4)

This produces

1
2
ans =
34

but is not the most elegant way of summing a single column. It is also possible to refer to the elements of a matrix with a single subscript, A(k). This is the usual way of referencing row and column vectors. But it can also apply to a fully two-dimensional matrix, in which case the array is regarded as one long column vector formed from the columns of the original matrix. So, for our magic square, A(8) is another way of referring to the value

15 stored in A(4,2). If you try to use the value of an element outside of the matrix, it is an error.

1
t = A(4,5)

Index exceeds matrix dimensions. On the other hand, if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer.

1
2
3
4
5
6
7
X = A;
X(4,5) = 17
X =
16  3  2  13  0
5  10  11  8  0
9  6  7  12  0
4  15  14  1  17

The Colon Operator

The colon, :, is one of MATLAB’s most important operators. It occurs in several different forms. The expression

1
1:10

is a row vector containing the integers from 1 to 10

1
1 2 3 4 5 6 7 8 9 10

To obtain nonunit spacing, specify an increment. For example,

1
100:-7:50

is

1
100 93 86 79 72 65 58 51

and

1
0:pi/4:pi

is

1
0 0.7854 1.5708 2.3562 3.1416

Subscript expressions involving colons refer to portions of a matrix.

1
A(1:k,j.html">j)

is the first k elements of the jth column of A. So

1
sum(A(1:4,4))

computes the sum of the fourth column. But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. So

1
sum(A(:,end))

computes the sum of the elements in the last column of A.

1
2
ans =
34

Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are sorted into four groups with equal sums, that sum must be

1
sum(1:16)/4

which, of course, is

1
ans = 34

The magic Function

MATLAB actually has a built-in function that creates magic squares of almost any size. Not surprisingly, this function is named magic.

1
2
3
4
5
B = magic(4)
B = 16  2  3  13
5  11  10  8
9  7  6  12
4  14  15  1

This matrix is almost the same as the one in the Dürer engraving and has all the same “magic” properties; the only difference is that the two middle columns are exchanged. To make this B into Dürer’s A, swap the two middle columns.   

1
 A = B(:,[1 3 2 4])

This says “for each of the rows of matrix B, reorder the elements in the order 1, 3, 2, 4.” It produces

1
2
3
4
5
A =  
16  3  2  13
5  10  11  8
9  6  7  12
4  15  14  1

Matlab Quick Search:

  • manipulating matrices in matlab
  • manipulate matrices in matlab
  • matrix amateur

Desktop Tools

March 12th, 2008 No Comments   Posted in Documents

This section provides an introduction to MATLAB’s desktop tools. You can also use MATLAB functions to perform most of the features found in the desktop tools. The tools are:

  • “Command Window”
  • “Command History”
  • “Launch Pad”
  • “Help Browser”
  • “Current Directory Browser”
  • “Workspace Browser”
  • “Array Editor”
  • “Editor/Debugger”

Command Window

MATLAB Command Window

Use the Command Window to enter variables and run functions and M-files.
For more information on controlling input and output, see “Controlling Command Window Input and Output” on next articles.

Command History

Matlab Command History

Lines you enter in the Command Window are logged in the Command History window. In the Command History, you can view previously used functions, and copy and execute selected lines.

To save the input and output from a MATLAB session to a file, use the diary function.

Running External Programs

You can run external programs from the MATLAB Command Window. The exclamation point character ! is a shell escape and indicates that the rest of the input line is a command to the operating system. This is useful for invoking utilities or running other programs without quitting MATLAB. On Linux, for example,
!emacs magik.m
invokes an editor called emacs for a file named magik.m. When you quit the external program, the operating system returns control to MATLAB.

Launch Pad

Launch Pad

MATLAB’s Launch Pad provides easy access to tools, demos, and documentation.

Help Browser

Use the Help browser to search and view documentation for all your MathWorks products. The Help browser is a Web browser integrated into the MATLAB desktop that displays HTML documents.

Help Browser

To open the Help browser, click the help button {mosimage} in the toolbar, or type helpbrowser in the Command Window.

The Help browser consists of two panes, the Help Navigator, which you use to find information, and the display pane, where you view the information.

Help Navigator

Use to Help Navigator to find information. It includes:

  • Product filterSet the filter to show documentation only for the products you specify.
  • Contents tabView the titles and tables of contents of documentation for your products.
  • Index tab Find specific index entries (selected keywords) in the MathWorks documentation for your products.
  • Search tabLook for a specific phrase in the documentation. To get help for a specific function, set the Search type to Function Name.
  • Favorites tab View a list of documents you previously designated as favorites.

Display Pane

After finding documentation using the Help Navigator, view it in the display pane. While viewing the documentation, you can:

  • Browse to other pages Use the arrows at the tops and bottoms of the pages, or use the back and forward buttons in the toolbar.
  • Bookmark pages – Click the Add to Favorites button in the toolbar.
  • Print pages – Click the print button in the toolbar.
  • Find a term in the page – Type a term in the Find in page field in the toolbar and click Go.

Other features available in the display pane are: copying information, evaluating a selection, and viewing Web pages.

For More Help

In addition to the Help browser, you can use help functions. To get help for a specific function, use doc. For example, doc format displays help for the format function in the Help browser. Other means for getting help include contacting Technical Support (http://www.mathworks.com/support) and participating in the newsgroup for MATLAB users, comp.soft-sys.matlab.{mospagebreak}

Current Directory Browser

MATLAB file operations use the current directory and the search path as reference points. Any file you want to run must either be in the current directory or on the search path.

Current Directory

A quick way to view or change the current directory is by using the Current Directory field in the desktop toolbar as shown below.

Matlab Current Directory

To search for, view, open, and make changes to MATLAB-related directories and files, use the MATLAB Current Directory browser. Alternatively, you can use the functions dir, cd, and delete.

Search Path

To determine how to execute functions you call, MATLAB uses a search path to find M-files and other MATLAB-related files, which are organized in directories on your file system. Any file you want to run in MATLAB must reside in the current directory or in a directory that is on the search path. By default, the files supplied with MATLAB and MathWorks toolboxes are included in the search path.

To see which directories are on the search path or to change the search path, select Set Path from the File menu in the desktop, and use the Set Path dialog box. Alternatively, you can use the path function to view the search path, addpath to add directories to the path, and rmpath to remove directories from
the path.

Workspace Browser

The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. You add variables to the workspace by using functions, running M-files, and loading saved workspaces.
To view the workspace and information about each variable, use the Workspace browser, or use the functions who and whos.

Matlab Workspace

To delete variables from the workspace, select the variable and select Delete from the Edit menu. Alternatively, use the clear function.

The workspace is not maintained after you end the MATLAB session. To save the workspace to a file that can be read during a later MATLAB session, select Save Workspace As from the File menu, or use the save function. This saves the workspace to a binary file called a MAT-file, which has a .mat extension.There are options for saving to different formats. To read in a MAT-file, select Import Data from the File menu, or use the load function.

Array Editor

Double-click on a variable in the Workspace browser to see it in the Array Editor. Use the Array Editor to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell arrays of strings that are in the workspace.

Matlab Array Editor

Editor/Debugger

Use the Editor/Debugger to create and debug M-files, which are programs you write to run MATLAB functions. The Editor/Debugger provides a graphical user interface for basic text editing, as well as for M-file debugging.

Matlab Editör and matlab debugger

You can use any text editor to create M-files, such as Emacs, and can use references (accessible from the desktop File menu) to specify that editor as the default. If you use another editor, you can still use the MATLAB Editor/Debugger for debugging, or you can use debugging functions, such as dbstop, which sets a breakpoint.

If you just need to view the contents of an M-file, you can display it in the Command Window by using the type function.

Matlab Quick Search:

  • load mdl file using data m file
  • MATLABs launch pad
  • beginner launchpad

more

March 6th, 2008 No Comments   Posted in Functions

more   Control paged output in command window.
more OFF disables paging of the output in the MATLAB command window.
more ON enables paging of the output in the MATLAB command window.
more(N) specifies the size of the page to be N lines.

When more is enabled and output is being paged, advance to the next
line of output by hitting the RETURN key;  get the next page of
output by hitting the spacebar. Press the “q” key to exit out
of displaying the current item.

diary

March 6th, 2008 No Comments   Posted in Functions

DIARY Save text of MATLAB session.
DIARY filename causes a copy of all subsequent command window input and most of the resulting command window output to be appended to the named file. If no file is specified, the file ‘diary’ is used.

DIARY OFF suspends it.
DIARY ON turns it back on.
DIARY, by itself, toggles the diary state.

Use the functional form of DIARY, such as DIARY(‘file’),
when the file name is stored in a string.