关系运算
>> A
A =
1 2
3 4
>> B
B =
1 3
4 2
>> A < B
ans =
0 1
1 0
>> A >= 2
ans =
0 1
1 1
Tuesday, September 23, 2008
index 问题
对于二维矩阵,可以用二维的下标引用,这是最直观,自然的。但是在内存中,matlab矩阵的存储次序如何呢,是一列一列的存的。比如,
>> 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
>> 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
MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. Taking the square root or logarithm of a negative number is not an error; the appropriate complex result is produced automatically. MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments. For a list of the elementary mathematical functions, type
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.
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 -
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
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
You can also assign a scalar to all entries of a submatrix. Try:
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
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
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))
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
验证一个命题
假设,C为mxn矩阵
则有
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
则有
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(m,n),B(m,n)为同型矩阵。
定义,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
定义,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
Subscribe to:
Posts (Atom)