Wednesday, October 1, 2008
Tuesday, September 23, 2008
index 问题
>> A = rand(2,5)
A =
0.4089 0.1436 0.0832 0.0304 0.7000
0.7080 0.8713 0.4617 0.7532 0.2145
在内存中,则是,
起始地址 Addr
Addr :0.4089
Addr +1:0.7080
Addr +2:0.1436
Addr +3:0.8713
Addr +4:0.0832
Addr +5:0.4617
。。。
所以,
>> A(6)
ans =
0.4617
>> A(2,3)
ans =
0.4617
MATLAB functions
help elfun
For a list of more advanced mathematical and matrix functions, type
help specfun
help elmat
Some of the functions, like sqrt and sin, are built in. Built-in functions are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions, like gamma and sinh, are implemented in M-files.
There are some differences between built-in functions and other functions. For example, for built-in functions, you cannot see the code. For other functions, you can see the code and even modify it if you want.
Several special functions provide values of useful constants.
pi
3.14159265...
i
Imaginary unit,
j
Same as i
eps
Floating-point relative precision,
realmin
Smallest floating-point number,
realmax
Largest floating-point number,
Inf
Infinity
NaN
Not-a-number
Infinity is generated by dividing a nonzero value by zero, or by evaluating well defined mathematical expressions that overflow, i.e., exceed realmax. Not-a-number is generated by trying to evaluate expressions like 0/0 or Inf-Inf that do not have well defined mathematical values.
The function names are not reserved. It is possible to overwrite any of them with a new variable, such as
eps = 1.e-6
and then use that value in subsequent calculations. The original function can be restored with
clear eps
>> help elfun
Elementary math functions.
Trigonometric.
sin - Sine.
sind - Sine of argument in degrees.
sinh - Hyperbolic sine.
asin - Inverse sine.
asind - Inverse sine, result in degrees.
asinh - Inverse hyperbolic sine.
cos - Cosine.
cosd - Cosine of argument in degrees.
cosh - Hyperbolic cosine.
acos - Inverse cosine.
acosd - Inverse cosine, result in degrees.
acosh - Inverse hyperbolic cosine.
tan - Tangent.
tand - Tangent of argument in degrees.
tanh - Hyperbolic tangent.
atan - Inverse tangent.
atand - Inverse tangent, result in degrees.
atan2 - Four quadrant inverse tangent.
atanh - Inverse hyperbolic tangent.
sec - Secant.
secd - Secant of argument in degrees.
sech - Hyperbolic secant.
asec - Inverse secant.
asecd - Inverse secant, result in degrees.
asech - Inverse hyperbolic secant.
csc - Cosecant.
cscd - Cosecant of argument in degrees.
csch - Hyperbolic cosecant.
acsc - Inverse cosecant.
acscd - Inverse cosecant, result in degrees.
acsch - Inverse hyperbolic cosecant.
cot - Cotangent.
cotd - Cotangent of argument in degrees.
coth - Hyperbolic cotangent.
acot - Inverse cotangent.
acotd - Inverse cotangent, result in degrees.
acoth - Inverse hyperbolic cotangent.
hypot - Square root of sum of squares.
Exponential.
exp - Exponential.
expm1 - Compute exp(x)-1 accurately.
log - Natural logarithm.
log1p - Compute log(1+x) accurately.
log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
pow2 - Base 2 power and scale floating point number.
realpow - Power that will error out on complex result.
reallog - Natural logarithm of real number.
realsqrt - Square root of number greater than or equal to zero.
sqrt - Square root.
nthroot - Real n-th root of real numbers.
nextpow2 - Next higher power of 2.
Complex.
abs - Absolute value.
angle - Phase angle.
complex - Construct complex data from real and imaginary parts.
conj - Complex conjugate.
imag - Complex imaginary part.
real - Complex real part.
unwrap - Unwrap phase angle.
isreal - True for real array.
cplxpair - Sort numbers into complex conjugate pairs.
Rounding and remainder.
fix - Round towards zero.
floor - Round towards minus infinity.
ceil - Round towards plus infinity.
round - Round towards nearest integer.
mod - Modulus (signed remainder after division).
rem - Remainder after division.
sign - Signum.
>> help elmat
Elementary matrices and matrix manipulation.
Elementary matrices.
zeros - Zeros array.
ones - Ones array.
eye - Identity matrix.
repmat - Replicate and tile array.
rand - Uniformly distributed random numbers.
randn - Normally distributed random numbers.
linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
freqspace - Frequency spacing for frequency response.
meshgrid - X and Y arrays for 3-D plots.
accumarray - Construct an array with accumulation.
: - Regularly spaced vector and index into matrix.
Basic array information.
size - Size of array.
length - Length of vector.
ndims - Number of dimensions.
numel - Number of elements.
disp - Display matrix or text.
isempty - True for empty array.
isequal - True if arrays are numerically equal.
isequalwithequalnans - True if arrays are numerically equal.
Matrix manipulation.
cat - Concatenate arrays.
reshape - Change size.
diag - Diagonal matrices and diagonals of matrix.
blkdiag - Block diagonal concatenation.
tril - Extract lower triangular part.
triu - Extract upper triangular part.
fliplr - Flip matrix in left/right direction.
flipud - Flip matrix in up/down direction.
flipdim - Flip matrix along specified dimension.
rot90 - Rotate matrix 90 degrees.
: - Regularly spaced vector and index into matrix.
find - Find indices of nonzero elements.
end - Last index.
sub2ind - Linear index from multiple subscripts.
ind2sub - Multiple subscripts from linear index.
bsxfun - Binary singleton expansion function.
Multi-dimensional array functions.
ndgrid - Generate arrays for N-D functions and interpolation.
permute - Permute array dimensions.
ipermute - Inverse permute array dimensions.
shiftdim - Shift dimensions.
circshift - Shift array circularly.
squeeze - Remove singleton dimensions.
Array utility functions.
isscalar - True for scalar.
isvector - True for vector.
Special variables and constants.
ans - Most recent answer.
eps - Floating point relative accuracy.
realmax - Largest positive floating point number.
realmin - Smallest positive floating point number.
pi - 3.1415926535897....
i - Imaginary unit.
inf - Infinity.
nan - Not-a-Number.
isnan - True for Not-a-Number.
isinf - True for infinite elements.
isfinite - True for finite elements.
j - Imaginary unit.
why - Succinct answer.
Specialized matrices.
compan - Companion matrix.
gallery - Higham test matrices.
hadamard - Hadamard matrix.
hankel - Hankel matrix.
hilb - Hilbert matrix.
invhilb - Inverse Hilbert matrix.
magic - Magic square.
pascal - Pascal matrix.
rosser - Classic symmetric eigenvalue test problem.
toeplitz - Toeplitz matrix.
vander - Vandermonde matrix.
wilkinson - Wilkinson's eigenvalue test matrix.
>> help specfun
Specialized math functions.
Specialized math functions.
airy - Airy functions.
besselj - Bessel function of the first kind.
bessely - Bessel function of the second kind.
besselh - Bessel functions of the third kind (Hankel function).
besseli - Modified Bessel function of the first kind.
besselk - Modified Bessel function of the second kind.
beta - Beta function.
betainc - Incomplete beta function.
betaln - Logarithm of beta function.
ellipj - Jacobi elliptic functions.
ellipke - Complete elliptic integral.
erf - Error function.
erfc - Complementary error function.
erfcx - Scaled complementary error function.
erfinv - Inverse error function.
expint - Exponential integral function.
gamma - Gamma function.
gammainc - Incomplete gamma function.
gammaln - Logarithm of gamma function.
psi - Psi (polygamma) function.
legendre - Associated Legendre function.
cross - Vector cross product.
dot - Vector dot product.
Number theoretic functions.
factor - Prime factors.
isprime - True for prime numbers.
primes - Generate list of prime numbers.
gcd - Greatest common divisor.
lcm - Least common multiple.
rat - Rational approximation.
rats - Rational output.
perms - All possible permutations.
nchoosek - All combinations of N elements taken K at a time.
factorial - Factorial function.
Coordinate transforms.
cart2sph - Transform Cartesian to spherical coordinates.
cart2pol - Transform Cartesian to polar coordinates.
pol2cart - Transform polar to Cartesian coordinates.
sph2cart - Transform spherical to Cartesian coordinates.
hsv2rgb - Convert hue-saturation-value colors to red-green-blue.
rgb2hsv - Convert red-green-blue colors to hue-saturation-value.
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位有效数字显示。