Thursday, September 11, 2008
Save workspace variables to disk
Save workspace variables to disk
Graphical Interface
As an alternative to the save function, select Save Workspace As from the File menu in the MATLAB® desktop, or use the Workspace browser.
Syntax
save
save filename
save filename content
save filename options
save filename content options
save('filename', 'var1', 'var2', ...)
Examples
Example 1
Save all variables from the workspace in binary MAT-file test.mat:
save test.mat
Example 2
Save variables p and q in binary MAT-file test.mat.
In this example, the file name is stored in a variable, savefile. You must call save using the function syntax of the command if you intend to reference the file name through a variable.
savefile = 'test.mat';
p = rand(1, 10);
q = ones(10);
save(savefile, 'p', 'q')
Example 3
Save the variables vol and temp in ASCII format to a file named june10:
save('d:\mymfiles\june10','vol','temp','-ASCII')
Example 4
Save the fields of structure s1 as individual variables rather than as an entire structure.
s1.a = 12.7; s1.b = {'abc', [4 5; 6 7]}; s1.c = 'Hello!';
save newstruct.mat -struct s1;
clear
Check what was saved to newstruct.mat:
whos -file newstruct.mat
Name Size Bytes Class
a 1x1 8 double array
b 1x2 158 cell array
c 1x6 12 char array
Grand total is 16 elements using 178 bytes
Read only the b field into the MATLAB workspace.
str = load('newstruct.mat', 'b')
str =
b: {'abc' [2x2 double]}
Example 5
Using regular expressions, save in MAT-file mydata.mat those variables with names that begin with Mon, Tue, or Wed:
save('mydata', '-regexp', '^Mon|^Tue|^Wed');
Here is another way of doing the same thing. In this case, there are three separate expression arguments:
save('mydata', '-regexp', '^Mon', '^Tue', '^Wed');
Example 6
Save a 3000-by-3000 matrix uncompressed to file c1.mat, and compressed to file c2.mat. The compressed file uses about one quarter the disk space required to store the uncompressed data:
x = ones(3000);
y = uint32(rand(3000) * 100);
save -v6 c1 x y % Save without compression
save -v7 c2 x y % Save with compression
d1 = dir('c1.mat');
d2 = dir('c2.mat');
d1.bytes
ans =
45000240 % Size of the uncompressed data in bytes.
d2.bytes
ans =
11985283 % Size of the compressed data in bytes.
d2.bytes/d1.bytes
ans =
0.2663 % Ratio of compressed to uncompressed
Monday, September 8, 2008
tips
A(:, [2 4]) = 99
You can delete rows or columns of a matrix by assigning the empty matrix ([]) to them. Try:
A(:, [2 4]) = []
>> x= rand(1,5)
x =
0.7513 0.2551 0.5060 0.6991 0.8909
>> x = x(end:-1:1)
x =
0.8909 0.6991 0.5060 0.2551 0.7513
Thursday, September 4, 2008
Basic 2-d Plot Commands
The basic command for plotting in Matlab is: plot(x,y). The important thing to remember is that in Matlab, variables such as x and y are matrices, which must be of the same size. The plot command simply creates a figure window and plots the data in the variable x versus those in y and interpolates linearly between the points. If x is a vector and y are a matrix, then plot(x,y) will plot the rows or columns of y versus the vector x, depending on whether the row or column length matches the length of x.
We are interested in using Matlab to plot functions. The important point is: all built in functions in Matlab are vectorized. This means that if x is a matrix, then the command sin(x) will create a matrix of the same size whose entries are computed by taking the sine of each entry of x. Hence, to create a plot of sin(x) on say the interval [-pi,pi] we would use:
>>x=-pi:pi/20:pi;
>>plot(x,sin(x))
The first line creates a vector of data for the independent variable; the step size is pi/20. To find out how long the vector is type
>>length(x) % no semicolon produces output
ans = 41 % this is the form of output
Alternatively, we could type
>>size(x)
ans = 1 41 % x is a row vector of length 41
Multiple plots on the same axis can be done in two ways.
>>x=-pi:pi/20:pi;
>>plot(x,sin(x))
>>hold on % this command forces the same set of axis for further plots
>>plot(x,cos(x))
>>grid on % places a grid on the axis
>>hold off % future plot commands will go to a new set of axis
Alternatively, the same thing can be accomplished with the command
>>plot(x,sin(x),x,cos(x))
Either way produces something like the following output.
Alternatively, one may wish to plot the two functions in the same figure window but on a different set of axes. The command is
>>subplot(1,2,1),plot(x,sin(x))
>>grid on
>>subplot(1,2,2),plot(x,cos(x))
>>grid on
NOTE: If you forget to type grid on, or any other axis command below after the first plot, simply click on the axis region and then type the command.
The output looks like:
Several observations are in order:
The x-axis ranges from -4 to 4, not matching the original data.
Except for color, we cannot distinguish between the graphs.
The axes are not labeled.
Are there other line styles?
There is no title on the figure.
Can we control the tick mark positions on the x and y axes?
Axis commands:
axis tight (Sets axis limits to the range of the plotted data).
axis([xmin xmax ymin ymax]) (Used before the plot command, sets the limits as given in the vector)
axis equal (Set the aspect ratio so that equal tick mark increments have the same size on each axis)
axis normal (Restore the axis box to full size and removes any restriction on scaling)
axis off (Turn off the axis, tick marks, and background)
axis on (Turn on the axis, tick marks, and background)
Line styles. The curves depicted in a given set of axis can have a variety of line styles. For example
>>plot(x,sin(x),x,cos(x),'--') % plots sin(x) and cos(x) on the same axis with cosine plotted with a dashed line
>>plot(x,sin(x),'LineWidth',2) % plots sin(x) with line thickness of 2 points; default is 0.5; possible choices 2,3,4.
Labeling the axis:
xlabel('string') % string represents the desired label
ylabel('string')
zlabel('string') % For use in 3-d plots
Annotating the plot:
legend('string1','string2',.....,m)
The strings string1, string2, etc are the desired labels for the different functions plotted. The variable m placed at the end specifies the position of the legend box: m=1, upper right hand corner, m=2 upper left hand corner, m=3 lower left hand corner, m=4 lower right hand corner, m=-1 to the right of the axis, without m specified the default is m=1.
gtext('string')
This command transforms the mouse pointer into crosshairs over the plot, when clicked over a desired position, the string will appear on the plot.
Plot title command:
title('string') % places string above the plot
gtext can be used as above for manual positioning of a title.
Tick mark values can be set with the command:
set(gca,'xtick',[vector of values])
gca means : get current axis object
'xtick' : could be 'ytick' or 'ztick'
[vector of values] : you specify the numerical values for the ticks.
Example: Sine & Cosine Plots
This example makes use of a variety of the above commands.
>>x=-pi:pi/20:pi;
>>plot(x,sin(x),x,cos(x),'--',2)
>>axis tight
>>legend('sin(x)','cos(x)',2)
>>title('An Example Plot')
>>xlabel('x'); ylabel('y')
>>set(gca,'xtick',[-3 0 3])
>>grid on
The output should look something like:
NOTE: Many of the plot refinements can be done from the figure window. Look under the Tool menu in the figure window. The tool bar also offers a variety of ways to edit the plot.
Example: Roots of an equation
Here we will obtain a plot of tan(pi*x) and -x. This is a graphical depiction of the roots of the equation tan(pi*x)=-x.
» x=-0.495:0.005:0.495; % vector for x
» x=[x x+1 x+2 x+3 x+4]; % making use of periodicity and avoiding singularities
» plot(x,tan(pi*x),'LineWidth',2)
» hold on
» axis([0 4.5 -6 4]) % adjusting the axis limits
» plot(x,-x) % plotting the line
» plot(x,zeros(length(x))) % plotting a horizontal line
» title('tan\pi\lambda = -\lambda')
» title('tan\pi\lambda = -\lambda : Graphical Depiction of Roots')
» gtext('\lambda_{1}')
» gtext('\lambda_{2}')
» gtext('\lambda_{3}')
» gtext('\lambda_{4}')
NOTE: In the last five lines we have used a LaTex interpreter built into Matlab for writing Greek letters. The backslash \ invokes the interpreter, LaTex command for Greek letters is to spell them, and the _{k} forces a subscript. The output looks as follows.
WARNING: In Matlab, the operand +, -, *, / are all matrix operations.
There is no problem with the first two: if x is a matrix, then x+5 simply adds 5 to every entry in x. However, if x and y are matrices of the same size, x*y performs matrix multiplication. If you want multiplication to be done element by element, the command is x.*y.
For example, if you want to plot the polynomial function (x^4-1)(x+3) on the interval [-4,2] one could write
>>x=-4:0.1:2;
>>plot(x,(x.^4-1).*(x+3))
Tuesday, September 2, 2008
验证一个命题
则有
trace(C'*C)=norm(C,'fro');
------
>> C = rand(3,3)
C =
0.4898 0.7094 0.6797
0.4456 0.7547 0.6551
0.6463 0.2760 0.1626
>> trace(C'*C)
ans =
2.9227
>> norm(C,'fro')*norm(C,'fro')
ans =
2.9227
--------
help norm
NORM Matrix or vector norm.
For matrices...
NORM(X) is the largest singular value of X, max(svd(X)).
NORM(X,2) is the same as NORM(X).
NORM(X,1) is the 1-norm of X, the largest column sum,
= max(sum(abs(X))).
NORM(X,inf) is the infinity norm of X, the largest row sum,
= max(sum(abs(X'))).
NORM(X,'fro') is the Frobenius norm, sqrt(sum(diag(X'*X))).
NORM(X,P) is available for matrix X only if P is 1, 2, inf or 'fro'.
For vectors...
NORM(V,P) = sum(abs(V).^P)^(1/P).
NORM(V) = norm(V,2).
NORM(V,inf) = max(abs(V)).
NORM(V,-inf) = min(abs(V)).
See also cond, rcond, condest, normest, hypot.
Overloaded methods:
lti/norm
distributed/norm
mfilt.norm
adaptfilt.norm
idmodel/norm
dfilt.norm
Reference page in Help browser
doc norm
用matlab验证一个命题
定义,A,B的内积A:B==对应元素相乘后求和。
用Matlab的语言即
A:B = sum(sum(A.*B))
其实A:B 还可用迹来表示,
A:B = trace(A'*B) = trace(B'*A)
利用矩阵的知识,上述命题证明是很简单的。
现用实验的办法,用MAtlab验证如下,
>> A = rand(3,3)
A =
0.7922 0.0357 0.6787
0.9595 0.8491 0.7577
0.6557 0.9340 0.7431
>> B = rand(3,3)
B =
0.3922 0.7060 0.0462
0.6555 0.0318 0.0971
0.1712 0.2769 0.8235
>> sum(sum(A.*B))
ans =
2.0797
>> trace(A'*B)
ans =
2.0797
>> trace(A*B)
ans =
2.0976
>> trace(B'*A)
ans =
2.0797
>> trace(B*A)
ans =
2.0976
Tuesday, August 19, 2008
Matlab - An Introduction to Combinatorics
Matlab - An Introduction to Combinatorics
This is a guest post by Will Dwinnell. Will Dwinnell is a senior-level data miner who shares with us a common love for Matlab. Daniel and I have enjoy reading his blog, and we are extremely excited to introduce Will to our readers.
Introduction
MATLAB is used in a many fields and consequently includes a diverse array of functions. Many useful functions go neglected by programmers who are unfamiliar with them. This article will briefly explore three functions which may come in handy from time to time, even if they never become everyday workhorses. Specifically, these functions deal with combinations of items.
The “perms” Command
The perms function accepts a list of items, and returns all possible orderings of these items. You may remember this from high school as a permutation problem. Here’s a simple example:
>> perms([1:3])
ans =
3 2 1
3 1 2
2 3 1
2 1 3
1 2 3
1 3 2
This function is simple enough, but spares one managing the loops this would otherwise require. One nice thing about perms is that it will accepts non-numeric data as cell array lists:
>> perms({'red', 'green', 'blue'})
ans =
'blue' 'green' 'red'
'blue' 'red' 'green'
'green' 'blue' 'red'
'green' 'red' 'blue'
'red' 'green' 'blue'
'red' 'blue' 'green'
This function might be useful in resource assignment problems, such as assigning sports teams their preferences of players, fields, etc., with teams selecting in the indicated order. Each time this round of selections takes place, the next row would be used.
The “randperm” Command
Many problems require the shuffling of a list of items. This comes up in randomizing the order of examples for machine learning systems, shuffing virtual cards in game programs and simulations. This can be accomplised using MATLAB’s widely used rand and sort functions:
>> MyList = [1:6]'
MyList =
1
2
3
4
5
6
>> [R Index] = sort(rand(6,1))
R =
0.1419
0.4218
0.4854
0.8003
0.9157
0.9572
Index =
4
5
2
3
6
1
>> MyList = MyList(Index)cle
MyList =
4
5
2
3
6
1
This is all unnecessarily complex, though, since randperm will do this in a single step:
>> MyList = [1:6]'
MyList =
1
2
3
4
5
6
>> MyList = MyList(randperm(6))
MyList =
4
3
1
5
6
2
randperm(n) returns the integers from 1 to n, in a random order:
>> randperm(8)
ans =
8 6 4 5 1 7 3 2
Note that randperm is driven by the same random number generator that feeds rand, so calling one will affect the subsequent output of the other, and both are seeded the same way.
The “nchoosek” Command
Pop quiz! How many ways are there to draw a hand of 5 cards from a deck of 52 cards, ignoring their order? I don’t remember how to calculate this either, but the nchoosek function will do it for you, and more!
When given scalar arguments, nchoosek(n,k) will return the number of combinations of n items, taken k at a time. For instance, if one needed to know how many ways 2 things could be drawn from a set of 6:
>> nchoosek(6,2)
ans =
15
Sometimes, though, what is needed is a list of the actual combinations. With a vector for its first argument, nchoosek will return all possible combinations:
>> nchoosek(1:6,2)
ans =
1 2
1 3
1 4
1 5
1 6
2 3
2 4
2 5
2 6
3 4
3 5
3 6
4 5
4 6
5 6
As with perms, this saves potentially much looping and other headaches for the MATLAB programmer. Also like perms, nchoosek will accept a cell array of strings as the list of items:
>> nchoosek({'chicken', 'fish', 'pizza', 'beef', 'soup', 'ratatouille'},2)
ans =
'chicken' 'fish'
'chicken' 'pizza'
'chicken' 'beef'
'chicken' 'soup'
'chicken' 'ratatouille'
'fish' 'pizza'
'fish' 'beef'
'fish' 'soup'
'fish' 'ratatouille'
'pizza' 'beef'
'pizza' 'soup'
'pizza' 'ratatouille'
'beef' 'soup'
'beef' 'ratatouille'
'soup' 'ratatouille'
Incidentally, there are over two and a half million distinct 5-card hands from a deck of 52:
>> nchoosek(52,5)
ans =
2598960
Closing Thoughts
Take care not to apply perms and nchoosek to calculations which are too large: the number of theoretically possible combinations or permutations can grow quite large.
It is often helpful to be familiar with parts of MATLAB which you may use less frequently. My recommendation is to occasionally glance through the help facility. Calling help by itself yields a list of sub-topics, such as elfun (elementary math), graph3d (”three dimensional graphs”) and strfun (”character strings”). Accessing help for any of these provides a list of functions which you should explore for future use.
About the Author
Will Dwinnell is a senior-level data miner who writes the Data Mining in MATLAB Web log. We suggest you visit his site and see what he has to offer. There are some very interesting articles there!
Monday, August 11, 2008
在matlab中如何控制数据的输出格式?(完整总结)
format
缺省时为默认短格式方式与format short相同
format short
短格式方式,显示5位定点十进制数。
format long
长格式方式,显示15位定点十进制数。
format short g
当数据大于1000或小于1时便会以科学记数法显示(-e),若想坚持用整数部分加小数部分的格式来显示,就要再后边加 g
format long g
format hex
十六进制格式方式。
format bank
银行格式。按元、角、分(小数点后具有两位)的固定格式。
format +
+格式,以+,—和空格分别表示中的正数,负数和零元素
format short e
短格式e方式,显示5位浮点十进制数
format long e
长格式e方式,显示15位浮点十进制数。
format rat
分数格式形式。用有理数逼近显示数据。如pi显示为355/113。
format loose
松散格式。数据之间有空行。
format compact
紧凑格式。数据之间无空行。
vpa(date,n)
将数据date以n位有效数字显示。