Special Variables
ans
dafault variable name for the rsult
pi
π : 3.1415926..
eps
ε : 2.2204e-16, smallest value by which two numbers can differ
inf
∞, Infinity
NAN or nan
not-a-number
Command involving variables
who
list the names of the defined variables
whos
list the names and sizes of defined variables
clear
clears all variables
clear [name]
clears the variable [name]
clc
clear the command window
clf
clears the current figure and the graph window
Vectors
The colon notation may be used to address a block of elements
(start:increment:end)
Example
>> x=[0 .25*pi .5*pi .75*pi pi]
x =
0 0.7854 1.5708 2.3562 3.1416
>> (1:2:5)
ans =
0 1.5708 3.1416
start:end
Create row vector x starting with start, counting 1, ending at end
start:increment:end
Create row vector x starting with start, counting by increment, ending at end
linspace(start,end,number)
Create linearly spaced row vector x starting with start, ending at end, having number elements
logspace(start,end,number)
Create logarithmically spaced row vector x starting with start, ending at end, having number elements
length(x)
Returns the length of vector x
x'
Transpose of vector x
dot(x,y), cross(x,y)
Returns the scalar dot and vector cross product of the vector x and y
Array Operations
Element-by-Element Array-Array Mathematics
Addition
a + b
Subtraction
a - b
Multiplication
a .* b
Division
a ./ b
Exponentiation
a .^ b
Matrices
Matrix Addressing
Matrix name(row, column)
Colon may be used in place of a row or column reference to select the entire row or column.
Some useful commands
zeros(n)
Returns a n X n matrix of zeros
zeros(m, n)
Returns a m X n matrix of zeros
ones(n)
Returns a n X n matrix of ones
ones(m, n)
Returns a m X n matrix of ones
size(A)
For a m X n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix
length(A)
Returns the larger of the number of rows or columns in A
More commands
Transpose
A'
Identity Matrix
eye(n)
returns an n X n identity matrix
eye(m, n)
returns an m X n matrix with ones on the main diagonal and zeros elsewhere
Additional and Subtraction
C = A + B
C = A - B
Scalar Multiplication
B = α A, where α is a scalar
Matrix Multiplication
A * B
Matrix Division
A \ B, Same as inv(A) * B
Matrix Inverse
inv(A), A must be a square matrix in this case
Matrix Powers
B = A * A, A must be a square matrix
Determinant
det(A), A must be a square matrix
Polynomials
The polynomials are represented by their coefficients in MATLAB
Consider the following polynomial:
A(x) = s³ + 3s² + 3s + 1
For s is scalar:
use scalar operations
A = S ^ 3 + 3 * s ^ 2 + 3 * s + 1;
For s is a vector or a matrix:
use array or element by element operation
A = S .^ 3 + 3 * s .^ 2 + 3 * s + 1;
Function polyval(a,s):
evaluate a polynomial with coefficients in vector a for the values in s
Operation
Addition
A + B
Sum of polynomial A and B, the coefficient vectors must have the same length.
Scalar Multiple
3 * A
Multiply the polynomial A by 3.
Polynomial Multiplication
conv(A, B)
Returns the coefficient vector for the resulting from the product of polynomial A and B.
Polynomial Division
[q, r] = deconv(A, B)
Returns the long division of A and B. q is the quotient polynomial coefficient, and r is the remainder polynomial coefficient.
Derivatives
polyder(A)
Returns the coefficients of the derivative of the polynomial A.
polyder(A, B)
Returns the coefficients of the derivative of the product of A and B.
[N, D] = polyder(B, A)
Returns the derivative of ratio B / A, represented as N / D.
Find Roots
roots(A)
Returns the roots of the polynomial A in column vector form.
Find Polynomials
Poly(r)
Returns the coefficient vector of the polynomial having roots r.
Plotting
For more information on 2-D plotting, type help graph2d
Plotting a point:
pot(variablename, 'symbol')
Commands for axes
axis([xmin xmax ymin ymax])
Define minimum and maximum values of the axes
axis square
Produce a square plot
axis equal
Equal scaling factors for both axes
axis normal
Turn off axis square, equal
axis auto
Return the axis to defaults
Plotting curves
plot(x, y)
generate a linear plot of the values of x (horizontal axis) and y (vertical axis)
semilogx(x, y)
generate a plot of the values of x (logarithmic scale) and y (linear scale)
semilogy(x, y)
loglog(x, y)
generate a plot of the values of x and y (both logarithmic scale)
Multiple curves
plot(x, y, w, z)
multiple curves can be plotted on the same graph: y vs. x and z vs. w
legend('string1', 'string2', ...)
used to distinguish between plots on the same graph
Multiple figures
figure(n)
use in creation of multiple plot windows before the command plot()
close
closes the figure n window
close all
closes all the plot windows
Sublplots
subplot(m, n, p)
m by n grid of windows, with p specifying the current plot as the pth window
Example: (polynomial function)
Plot the polynomial using linear/linear, log/linear, linear/log, log/log scale
y = 2x² + 7x + 9
>> % generate the polynomial:
>> x=linspace(0, 10, 100);
>> y=2*x.^2+7*x-9;
>> figure(1);
>> subplot(2,2,1), plot(x,y)
>> title('polynomial, linear/linear scale');
>> ylabel('y'),grid;
>> subplot(2,2,2), semilogx(x,y);
>> title('polynomial, log/linear scale');
>> ylabel('y'),grid;
>> subplot(2,2,3), semilogy(x,y);
>> title('polynomial, linear/log scale');
>> ylabel('y'), grid;
>> subplot(2,2,4), loglog(x,y);
>> title('polynomial, log/log scale');
>> ylabel('y'),grid;
Adding new curves to the existing graph, use the hold command to add lines/points to an existing plot
hold on
retain existing axes, add new curves to current axes.
hold off
release the current figure windows for new plots.
Grid and labels
grid on
Add dashed grids lines at the tick marks
grid off
Removes grid lines (default)
grid
Toggles grid statues (off to on or on to off)
title('text')
Labels top of plot with text
xlabel('text')
Labels horizontal (x) axis with text
ylabel('text')
Labels vertical (x) axis with test
text(x, y, 'text')
Adds text to location (x, y) on the current axes, where (x, y) is in units from the current plot
Programming
Flow control and loops
Simple if statement:
if logical expression
commands
end
Example: (Nested)
if d < 50
count = count + 1;
disp(d);
if b > d
b = 0;
end
end
Example: (else and elseif clauses)
if temperature > 100
disp('Too hot - equipment malfunctioning.');
elseif temperature > 90
disp('Normal operating range.');
elseif temperature > 75
disp('Below desired operating range.');
else
disp('Too cold - Turn off equipment.');
end
The switch statement:
switch expression
case test expression 1
commands
case test expression 2
commands
otherwise
commands
end
Example: (switch interval)
case 1
xinc = interval / 10;
case 0
xinc = 0.1;
otherwise
disp('wrong value');
end
Loops
for loop
for variable = expression
commands
end
while loop
while expression
command
end
Example: (for loop)
for t = 1 : 5000
y(t) = sin( 2 * pi * t / 10 );
end
Example: (while loop)
while EPS > 1
EPS = EPS / 2
end
the break statement
break - is used to terminate the execution of the loop
M-Files
Before, we have executed the commands in the command window. The more general way is to create a M-file
The M-file is a text file that consists a group of MATLAB commands.
MATLAB can open and execute the commands exactly as if they were entered at the MATLAB command window.
To run the M-files, just type the file name in the command window. (make sure the current working directory is set correctly)
User-Defined Function
Add the following command in the beginning of your m-file:
function [output variables] = function_name (input variables);
Note: the function_name should be the same as your file name to avoid confusion.
Calling your function
A user-defined function is called by the name of the m-file, not the name given in the function definition.
Type in the m-file name like other pre-defined commands.
Comments:
The first few lines should be comments, as they will be displayed if help is requested for the function name. the first comment line is reference by the lookfor command.
Example: ( circle1.m ) // 이거 디버깅하느라 고생함 ㅠㅠ
function y = circle1(center, radius, nop, style)
% circle1 draws a circle with center defined as a vector 'center'
% radius as a scalar 'radius'. 'nop'is the number of points on the circle
% 'style' is the style of the point
% Example to use: circle1([1 3], 4, 500, ':');
[m, n] = size( center );
if( ~( ( m == 1 ) || ( n == 1 ) ) || ( m == 1 && n == 1 ) )
error('Input must be a vector')
end
close all
x0 = center(1);
y0 = center(2);
t0 = 2 * pi / nop;
axis equal
axis([x0-radius-1 x0+radius+1 y0-radius-1 y0+radius+1])
hold on
for i = 1 : nop + 1
pos1 = radius * cos( t0 * ( i - 1 ) ) + x0;
pos2 = radius * sin( t0 * ( i - 1 ) ) + y0;
plot( pos1, pos2, style );
end
'Mechanical Engineering > Matlab' 카테고리의 다른 글
General Purpose Commands (0) | 2014.01.08 |
---|---|
Fundamental MATLAB Classes (0) | 2013.04.06 |
Chebyshev polynomials Tn (1) | 2013.04.06 |
How to Modeling Simulink OED(Ordinary Differential Equation) (0) | 2013.04.05 |
Simulink Shortcuts (0) | 2013.04.05 |