Download Matlab - מחברת קורס גרסה 10 - קובץ PDF

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Laplace–Runge–Lenz vector wikipedia , lookup

Euclidean vector wikipedia , lookup

System of linear equations wikipedia , lookup

Covariance and contravariance of vectors wikipedia , lookup

Linear least squares (mathematics) wikipedia , lookup

Rotation matrix wikipedia , lookup

Determinant wikipedia , lookup

Eigenvalues and eigenvectors wikipedia , lookup

Matrix (mathematics) wikipedia , lookup

Jordan normal form wikipedia , lookup

Principal component analysis wikipedia , lookup

Singular-value decomposition wikipedia , lookup

Orthogonal matrix wikipedia , lookup

Perron–Frobenius theorem wikipedia , lookup

Non-negative matrix factorization wikipedia , lookup

Ordinary least squares wikipedia , lookup

Four-vector wikipedia , lookup

Cayley–Hamilton theorem wikipedia , lookup

Gaussian elimination wikipedia , lookup

Matrix multiplication wikipedia , lookup

Matrix calculus wikipedia , lookup

Transcript
MATLAB R2013b
Guyaros Notebook
Matlab Guyaros Notebook Page 1
Ctrl+c
Stop calculation
Print last command
ctrl+r
Comments
ctrl+t
Uncomments
Crtl+s
Save
F9
Evalualte selction
Ctrl+enter
Run section
Matlab Guyaros Notebook Page 2
lookfor
lookfor
help
help
whos
Matlab Guyaros Notebook Page 3
;
Suppress output
%
Notes
%%
Create Cell of code
format compact
Suppresses excess line feeds to show more
output in a single screen
format short
Short fixed decimal format, with 4 digits after
the decimalpoint.
format long
Long fixed decimal format, with 15 digits after
the decimalpoint for double values, and 7 digits
after thedecimal point for single values.
format shorteng
Engineering format that has at least 5 digits
and a power that is a multiple of three
format longeng
Engineering format that has exactly 16
significant digits and a power that is a multiple
of three.
format bank
Fixed format for dollars and cents.
clear
Clear Workspace memory
clear a
Clear specific varible
clc
Clear Screen
clf
Clear figure
Workspace
a
command windows
Matlab Guyaros Notebook Page 4
pi
3.1416
exp(1)
e=2.7183
exp(x)
i
j
eps
realmin
realmax
inf
Matlab Guyaros Notebook Page 5
e
sqrt(x)
Square root
factorial(x)
Factorial
exp(x)
Exponenet
log(a)
Natural logarithm
log10(a)
Common (base 10) logarithm
rem(x,y)
Reminder
if rem(i,2)==1
number=odd;
elseif rem(i,2)==0
number=even;
end
Check if number is odd or even
mod(x,y)
Modulus after division
abs(x)
Absolute value
sum(x)
Sum
X
e
i
i
x
sum(x)
mean()
Average or mean value
tic
Start a stopwatch timer.
X
tic
toc
toc
lcm(a,b)
Least common multiple
the least common multiple of
corresponding elements of
A and B. The arrays A and B
must contain positive integers
and must be the same size
primes(N)
Generate list of prime numbers
Matlab Guyaros Notebook Page 6
N
1<4
Smaller Than
2>1
Grater Than
1<=1
Smaller or Equal
>=1
Grater or equal
1==1
Equal
5~=4
Not Equal
Or
&
AND
~
Not
Matlab Guyaros Notebook Page 7
round(X)
Round towards nearest integer
floor(X)
Round towards minus infinity
ceil()
Round towards plus infinity
fix()
Round towards zero
round(pi*10)/10
pi=pi
round(pi)
round(pi*10)/10
round(pi*100)/100
round(pi*1000)/1000
round(pi*10000)/10000
Matlab Guyaros Notebook Page 8
sin(x)
Sine in Radians
sind(x)
Sine in Degree
sinh(x)
Hyperbolic sine
asinh(x)
Inverse hyperbolic sine
asin(x)
Inverse sine in Radians
asind(x)
Inverse sine in Degrees
cos(x)
Cosine of arguments in Radians
cosd(x)
Cosine in Degree
cosh(x)
Hyperbolic cosine
tan(x)
Tangent in Radians
tand(x)
Tangent in Degrees
atand(x)
Inverse Tangent in Degrees
Matlab Guyaros Notebook Page 9
[1 2 3]
Create Row vector
Option#2
[1,2,3]
[1;2;3;4;5;6]
Create Column vector
[0:2:10]
[min;jump;max]
[
]
linspace(a,b,n)
a=
b=
n=
Linearly spaced vector
n
n
increment)
matrix2x2=[1 2 3;4 5 6]
Create Matrix
matrix4x4=
[1 2 3 4;5 6 7 8;9 10 11
12;13 14 15 16]
eye(n)
Unit matrix
nXn
eye(m,n)
Unit matrix in mXn
diemension
ones(n)
Ones matrix
Matlab Guyaros Notebook Page 10
ones(n)
Ones matrix
nXn
ones(m,n)
mXn
zeros(n)
Zeros matrix
zeros(m,n)
Zeros matrix, in mXn
dimension
diag(V)
magic(N)
mXn
Diagonal matrices and
diagonals of a matrix
V
Magic square
v1= [3 3 3 3 3 3 ]
v2= [8 8 8 8 8 8 ]
Y
v1
Y=zeros(1,12);
even=[2:2:12];
odd=[1:2:12];
Y([1],even)=v1;
Y([1],odd)=v2;
Y
v2
Matlab Guyaros Notebook Page 11
A'
Transpose
B(N)=[]
Delete index from matrix
B
N
A(:)
Create Col vector from
matrix
matrix([1,2],:) =
matrix([2,1],:)
Interchange rows
B([1,2],:) = A([1,2],:)
Matrix rows merge
Matlab Guyaros Notebook Page 12
A
B([1,2],:) = A([1,2],:)
Matrix rows merge
B(:,[1,3]) = A(:,[2,4])
Matrix Cols merge
matrix(row,:)=[]
Delete Row of matrix
matirx(:,col)=[]
Delete Col of matrix
matrix(row,:)=[1]
Change Row of matrix
Matlab Guyaros Notebook Page 13
matrix(row,:)=[1]
Change Row of matrix
reshape(matrix,rows,cols) Reshape vector to
matrix
mXn=NumberOfVectorElements
reshape(A,m,[])
A
m
mXn
m
C=[A;B]
.
C
A
B
C=[A,B;]
Matlab Guyaros Notebook Page 14
C=[A,B;]
B
fliplr()
flipud()
C
A
fliplr Flip matrix in
left/right direction
Flip matrix in up/down
direction
flip=v(end:-1:1)
fliplr()
flip=A(end:-1:1)
flip
rot90(A)
Rotate matrix 90 degree
Matlab Guyaros Notebook Page 15
rot90(A,k)
Rotate matrix 90 degree
K
Matlab Guyaros Notebook Page 16
A(i,j)
Print the element that
locate in
Row i
Col j
i
j
vector([Na,Nb,Nc,Nd])
matrix(N)
Print the element with
index N
N
N
matrix([Na,Nb,Nc])
N
matrix([1,2,3,4,9])
Print the
first,second,third,fourt
h,ninth elements of a
matrix
1,2,3
matrix([1],[1 2 3])
1,2,3
matrix([2,3],[3])
2,3
Matlab Guyaros Notebook Page 17
matrix([1,3,5],:)
Print specific rows
from a matrix
1,3,5
matrix(row, col:end)
Print entire Row from
matrix
matrix(row:end, col)
Print entire Col from
matrix
matrix(rowStart:RowEnd:J)
J
Matlab Guyaros Notebook Page 18
matrix(rowStart:RowEnd:J)
J
rowStart
RowEnd
max(vector)
Print largest
component from
vector
[maxValue N]=max(vector)
N
max(matrix)
max(matrix')
min(vector)
Print row vector
containing the
maximum element
value from each
column
Print row vector
containing the
Maximum element
value from each Row
Print Smallest
component from
vector
min(matrix)
Matlab Guyaros Notebook Page 19
min(matrix)
min(matrix')
A=magic(6)
[r c]=find(A<=12 & A>=8)
coords=[r,c]
for i=1:length(r)
w(i)=A(r(i),c(i));
end
w
Matlab Guyaros Notebook Page 20
[row,col]=find(B)
Find indices of
nonzero elements
find(B>N)
N
B>N
[row,col]=find(B>N)
N
find(B,k)
Matlab Guyaros Notebook Page 21
find(B,k)
k
find(B,k,'last')
values=matrix(find(matrix>N))
A(find(A~=N))
A(find(A==N))
k
Find and Bring
values from
vector/matrix that
qualify the
condition
x=[1,1.2,18,7,7]
values=x(x<7)
matrix==x
matrix~=x
matrix>x
matrix>=x
Matlab Guyaros Notebook Page 22
matrix<=x
x=[5:5:50]
y=10.*x
x
w=y(x==20)
w=y(4)
y
Matlab Guyaros Notebook Page 23
sort(vector)
Sort in ascending order
sort(vector,'descend')
Sort in descending order
sort(matrix)
Sort matrix column
sort(matrix')'
Sort matrix rows
unique(vector)
Delete repetitions
[filterV Nlocations]=unique(V)
N
filterV
filterV
Matlab Guyaros Notebook Page 24
Nlocations
length(vector)
Print the Length of
a vector
[m,n]=size(matrix)
Print matrix size
[rows cols]=size(matrix)
1x2
Matlab Guyaros Notebook Page 25
sum(x)
Sum of vector or
matrix
x
sum(x)
trace(matrix)
Sum of diagonal
elements
cumsum(matrix) cumsum Cumulative
sum of elements
mean(vector)
Mean value of the
vector elements
mean(matrix)
Row vector
containing the mean
value of each column
mean(matrix')' Col vector containing
Matlab Guyaros Notebook Page 26
X
mean(matrix')' Col vector containing
the mean value of
each row
Matlab Guyaros Notebook Page 27
rand(N)
rand(m,n)
randi(IMAX,m,n)
Returns an N-by-N matrix
containing pseudorandom values
drawn from the standard uniform
distribution on the open
interval(0,1)
NxN
Uniformly distributed
pseudorandom numbers
mXn
Pseudorandom integers from a
uniform discrete distribution
mXn
IMAX
r= a+(b-a).*rand(N)
N
b
r= round(a+(b-a).*rand(N))
a
N
Matlab Guyaros Notebook Page 28
r= round(a+(b-a).*rand(N))
N
b
rng('default')
Control the random number
generator used by matlab.
Matlab Guyaros Notebook Page 29
a
A*B
A *B
element-by-element multiply
A/B
A./B
element-by-element division
A^B
A.^B
A*B
A.*B
element-by-element
Matrix Multipication
Multiplying element-byelement
A./B
Matlab Guyaros Notebook Page 30
A./B
A\B
A/B=A*inv(B)
A^B
A.^B
Matlab Guyaros Notebook Page 31
dot(u,v)
Vector dot product
returns the scalar product
of the vectors
v u
cross(u,v)
Vector cross product
u,v
u,v
u,v
norm(u)
Calculate vector Magnitude
A+B
A-B
A*B
B
B
A
A
:
Matlab Guyaros Notebook Page 32
A\B
B
B
A'
Transpose
linsolve(A,b)
A
b
A\b
Solve linear system using
A "Backslash" sign
b
inv()
Inverse matrix
X=inv(A)*b
Solve linear equations using
inverse function
linsolve()
X
Matlab Guyaros Notebook Page 33
X
A
b
det()
Determinant
adjointA=inv(A)*det(A)
A
A
A
rref(matrix)
Reduced Row Echelon
Form
trace(matrix)
Sum of diagonal elements
rank(matrix)
Print matrix rank
svd()
Singular value
decomposition
Matlab Guyaros Notebook Page 34
while flag<10
a=a*flag;
flag=flag+1
end
Repeat statements an indefinite
number of times
if expression1
statements1
elseif expression2
statements2
else
statement3
end
%if statment must be finished with "end"
Conditionally execute statements
for i=start:n
teta=teta+(2*pi/n);
end
Repeat statements a specific
number of times
for
i
for i=start:inc:end
do_some_task(i)
end
for
inc
break
Terminate execution of WHILE or
FOR loop.
return
Matlab Guyaros Notebook Page 35
i
A=magic(5)
[rows,cols]=size(A)
B=A;
A
A
B
for j=1:cols
for i=1:rows
if A(i,j)>10
B(i,j)=0;
end
end
end
B
Matlab Guyaros Notebook Page 36
string='Hello World'
.
Create a String
string'
Transpose
string(n)
n
str2num()
Convert string
matrix to numeric
array
num2str()
Convert numbers
to a string
Matlab Guyaros Notebook Page 37
S=num2str(N)'
.
digits=str2num(S)
N
S
digits
digits
sum(digits)
sum(S)
S
ASCII
char(x)
double('GuYaros')
Convert Integer to
charcter According
to the ASCII table
x
Convert string to
Row Vector of
ASCII codes
Fstring='2*sin(x)*cos(x)'
V=double(Fstring)
char(Fstrin
double
char
Matlab Guyaros Notebook Page 38
match=(str1==str2)
Nlocations=find(str1==str2)
N
strcmp(s1,s2)
compares the
strings S1 and
S2 and returns
logical 1
(true) if they
are identical, and
returns logical 0
(false) otherwise.
strncmp(s1,s2,N)
Compare first N
characters of
strings.
Matlab Guyaros Notebook Page 39
N
N
N
NUM=input('Enter Number:')
Prompt for user input.
Matalab print the 'string' to
screen and then waits for input
from the keyboard
the user must type a Number.
STRING=input('Type:','s')
Prompt for user input.
Matalab print the 'string' to
screen and then waits for input
from the keyboard
the user must type a String.
disp(['string'])
Display array of strings
disp(['Tire Side Wall:
',num2str(tireSideWall),'[%]'])
Matlab Guyaros Notebook Page 40
function [ output_args ] = Untitled2( input_args )
User-Defined
function syntax
script
function [B] = my1stfun( A,n )
function [ T,x_t,y_t,peak,range ] = trajectory( x0,y0,theta,v0,g )
Matlab Guyaros Notebook Page 41
b
g
r
c
m
y
k
O
X
:
-.
s
d
V
<
p
h
plot(x,y)
plots graph vector Y versus vector X
plot(x,y,'r')
plot(x,y,'r--')
plot(x,y,'bO')
plot(x,y,'gX')
plot(x,y,'k.','markersize',1)
plot(x,y,'r*')
plot(x,y,'ko-.')
plot(x,y,'color',[1,0.6,0.6]')
RGB
[x,y,z]
x,y,z
plot(x,y,'b','LineWidth',2)
plot(x,y,'-rs','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',10)
figure(2)
Create new figure window
hold on
hold off
hold
grid on
Grid lines on
grid off
Grid lines off
title('Graph Title','FontSize',18)
legend('LineName1','LineName2')
Display legend
xlabel('Value [units]', 'FontSize', 1 )
X
ylabel('Value [units]')
Y
set(gca,'FontSize',18)
axis([Xmin,Xmax,Ymin,Ymax])
Control axis scaling and appearance
axis auto
Restore axis to defult state
xlim([Xmin,Xmax])
Sets the x axis limits
X
Ylim([Ymin Ymax])
Sets the y axis limits
Y
set(gca,'XTick',[start:jump:end])
set(gca,'YTick',[start:jump:end])
set(gca,'XTick',[1000:500:7500])
set(gca,'YTick',[0:10:220])
subplot(m,n,p)
m number of rows
n number of cols
p the plot index
Breaks the Figure window into an m-byn matrix of small axes
subplot(1,2,2)
Create axes in tiled positions
Plot
subplot
subplot(2,2,1)
text(x,y,'string')
Insert Text annotation to location (x,y)
(x,y)
text(x,y,'\leftarrow Comment')
text(-2,10,'\bf BOLD')
gtext(['click to insert text box'])
position a text annotation at a specific
point inthe data space with the mouse
[x,y]=ginput()
Graphical input from mouse.
bar(x,y)
Bar graph
Matlab Guyaros Notebook Page 42
3D
plot3(x,y,z)
Plot lines and points in 3-D space
plot3(x,y,z,'k')
Plot3([x1 y1], [x2 y2],[z1 z2])
xlabel('X', 'FontSize', 12)
ylabel('Y', 'FontSize', 12)
zlabel('Z', 'FontSize', 12)
view(AZ,EL)
3-D graph viewpoint specification
Set the angle of the view from which an
observer sees the current 3-D plot.
rotate3D
AZ,EL
for i=1:50
pause(0.2)
view(-2*i,28+0.1*i)
end
[xx,yy]=meshgrid(x,y)
Create a rotating viewpoint
Panning
Cartesian grid in 2-D/3-D space
x
y
zz= releation with x and y
mesh(xx,yy,zz
Z
meshc(xx,yy,zz)
surf(xx,yy,zz)
Z
surfc(xx,yy,zz)
Z
surf
contour3(xx,yy,zz)
shading FLAT
Colorbar
Z
Matlab Guyaros Notebook Page 43
polyval(P,X)
Evaluate polynomial
X
N
P = Vector in length N+1
X = matrix / vector
p(x) = 3x^2+2x+1
x=3,2,1
X
p=[3,2,1]
x=[5,7,9]
polyval(p,x)
roots(P)
Find polynomial roots
X
conv(P1,P2)
Convolution and polynomial
multiplicatio
[P,r]=deconv(P1,P2)
Polynominals Division
P1/P2
r
polyder(P)
Returns the derevative of the
polynominal P
polyint(P)
Integrate polynomial
analytically
polyfit(x,y,n)
Finds the coefficients of a
polyniminal p(x) of degree n
that fits the data
x,y
n
x
y
x
y
Matlab Guyaros Notebook Page 44
diff(X)
Difference and approximate
derivative
diff(fx,N)
N
diff(y)./diff(x)
YX
.
x2-x1
y2-y1y
X
X
Y
diff
plot
X
X=x(2:end)
diff('function',sym('mishtaneHaGzira'),dervativeorder)
Or
diff(String,sym('mishtaneHaGzira'),dervativeorder)
Examples:
diff('x*sin(x)',sym('x'),2)
diff(S,sym('t'),1)
sym
x
Fplot(FUN,LIM)
ydx=char(ydx)
polyder(P)
Returns the derevative of the
polynominal P
ini=int('x*sin(x)',sym('x'),2)
sym
trapz(x,y)
Trapezoidal numerical
integration
quad('FUN',a,b)
Numerically evaluate
integral, adaptive Simpson
quadrature.
x
a,b
a,b
quadl('FUN',a,b)
Numerically evaluate
integral, adaptive Lobatto
quadrature
Lobatto
x
a,b
polyint(P)
Integrate polynomial
analytically
Matlab Guyaros Notebook Page 45
a,b
fplot(FUN,LIM)
Example:
fplot('sin(t)*(cos(t))^2',[0 10],'r')
plots the function FUN between the x-axis limits
specified by LIMS = [XMIN XMAX]
ezplot('x^2-y^4')
plots the function FUN(X) over the default
domain
-2 PI < X < 2*PI
LIM
Hold on
plot
fzero(FUN,X0)
Tries to find a zero of the function FUN near X0
if X0 is a scalar
XO
fminsearch(FUN,X0)
starts at X0 and attempts to find a local minimizer
X of the function FUN
Y
X
X0
fminbnd()
Matlab Guyaros Notebook Page 46
interp1(x,y,alpha,'liner')
Interpolation
linear interpolation
X
y
X
Y
alpha
interp1(x,y,alpha,'nearest')
Interpolation
nearest neighbor
interpolation
nearest
alpha
interp1(x,y,alpha,'spline')
interp1(x,y,alpha,'cubic')
Interpolation
piecewise cubic spline
interpolation
Interpolation
shape-preserving piecewise
cubic interpolation
Matlab Guyaros Notebook Page 47
spline
cubic