مقدمة عن MATLAB MATLABأو ( )matrix laboratoryهو برنامج هندسي متقدم يقوم بإجراء العمليات الحسابية ومحاكاة النظمة المختلفة لذا يستخدم كوسيلة تحليل في عدة مجالت مثل العلوم و الرياضيات المتقدمة و في الصناعة كأداة بحث وتصميم ذات مردود عالي.
يستعمل البرنامج للغراض التالية: • إجراء العمليات الحسابية المعقدة بسرعة فائقةMath and . computation • •
اشتقاق اللوغاريتمات Algorithm development محاكاة وتصميم النظمة المختلفة في جميع فروع العلوم و الصناعة & Modeling simulation System
• تحليل البيانات و استكشافها Data analysis and exploration • رسم المجسمات الهندسية و الصناعية ذات الثلثة أبعاد (Three dimension )3D يعتبر MATLABمن البرامج ذات الستجابة السريعة حيث عنصر
البيانات الساسي فيه عبارة عن مصفوفة بدون أبعاد قياسية .لذلك يمكن استخدامه في حل معظم المسائل الحسابية المعقدة بسهولة وفي زمن قصير مقارنةً باستخدام لغات البرمجة الخرى مثل Cأو . FORTRAN
مكونات
MATLAB
من خمسة أجزاء رئيسية و هي :
يتكون برامج MATLAB .1لغة البرمجة MATLAB language
وهي عبارة عن لغة برمجة جاهزة ومكونة من ملفات فرعية تستخدم فيها المصفوفات و المحددات و الدوال الجبرية . .2محيط العمل working environment عبارة عن مجموعة وسائل و تسهيلت تستخدم لتمكين المستخدم من العمل . يحتوي هذا المحيط على وسائل لتنظيم و إدارة المتغيرات كما يقوم بجلب و إرسال المعلومات . .3منظم الرسوم البيانية :graphics Handle وهو عبارة عن منظومة رسم تجسيمي يحتوي على أوامر لرسم المجسمات ذات البعدين و الثلثة أبعاد .كما يحتوي على أوامر لظهار المجسمات وتحريكها . .4مكتبة MATLABللدوال الرياضية تحتوي علي الدوال التالية: Fast Fourier transforms , matrix eigenvalues , matrix inverse , cosine , sine , sum
Application program interface.5
عبارة عن وسائل مساعدة تسمح بربط البرامج المعدة بلغات أخرى مثل )Fortranو ( Cمع .MATLAB وسائط MATLABالمساعدة يحتوي ( )MATLABعلى وسائل مساعدة للتطبيقات المتخصصة و تسمى ( )Toolboxesالتي تساعد على القيام بدراسةٍ أوسع في مجالت الصناعة و استخدام التكنولوجيا المتخصصة . هذه الوسائل المساعدة ( )Toolboxesهي عبارة عن مجموعات شاملة من دوال (مشتقات) MATLABتعرف ب ( )M-Filesالتي تعطي MATLABقدرات كبيرة لحل مسائل معقدة ذات طابع خاص . هناك عدة وسائل مساعدة Toolboxesتستخدم ضمنيا مع MATLABمنها : [SIMULINK TOOLBOX [2] CONTROL SYSTEM TOOLBOX[1 [SIGNAL PROCESSING TOOLBOX [4] COMMUNICATION TOOLBOX [3 [MODEL PREDICTIVE CONTROL TOOLBOX[5 Toolboxes MATLAB
توضيح لبعض الوسائط المساعدة لي :MATLAB Communication Toolbox
عبارة عن وسائل مدمجة تستخدم لتصميم و تحليل و محاكاة أنظمة التصالت المختلفة وهي مفيدة في العديد من مجالت أبحاث التصالت مثل التصالت السلكية و اللسلكية وكذلك التصالت الرقمية و الفضائية و القمار الصناعية Control system Toolbox
تستخدم في تصميم و محاكاة أنظمة التحكم اللي مثل التحكم في العمليات النفطية و التحكم في المراكب الفضائية و غرف التحكم في المصانع الكبرى و العديد من الجهزة المتداولة كالغسالت الكهربائية التوماتيكية . Model predictive control Toolbox
يستخدم في تطبيقات أنظمة التحكم اللي ذات المداخل و المخارج المتعددة كما هو الحال في الهندسة الكيميائية و التحكم في العمليات
مقدمة عن
SIMULINK TOOLBOX
SIMULINKهو برنامج مصاحب لل MATLABذو استجابة فائقة لتحليل و محاكاة النظمة الديناميكية ] الخطية والغير خطية [ . يعتبر برنامج SIMULINKمن اكثر برامج الحاسوب الهندسية شيوعاً و استخداماً في مجالت البحاث الكاديمية و الصناعية لبناء نماذج تقليدية
للنظمة الديناميكية و تحليلها و محاكاتها .يمكن للباحث باستخدام هذا البرنامج بناء نماذج للنظمة الحقيقية و محاكاتها كما يمكن تعديل متغيرات هذه النظمة أثناء المحاكاة و ملحظة التغيرات التي تحدث على المنظومة . في هذا البرنامج تتم عملية بناء النماذج باستخدام المخططات الصندوقية المخزنة فيه على عكس البرامج الخرى و التي تستهلك جهد ووقت الباحث في كتابة برامج طويلة و معقدة مثل ] Cأو . [ Fortran هناك العديد من المخططات الصندوقية مخزنة في SIMULINKجاهزة للستعمال كما هو موضح في الجدول رقم (. )1 عند اكتمال بناء نموذج للمنظومة تبدأ عملية المحاكاة و ذلك باختيار طريقة التكامل المناسبة فبرنامج SIMULINKيحتوي على عدة طرق لنجاز عملية التكامل ( . )Integrationو يمكن مشاهدة النتائج أثناء عملية المحاكاة على هيئة منحنيات و ذلك باستخدام راسم الشارات الموجود أصلً في برنامج . SIMULINK Out
In
Connections Demos
Nonlinear
Linear
Discrete
Sinks
Simulink Block Library Copyright (c) 199097 by The MathWorks, Inc.
Sources &Blocksets Toolboxes
استخدام
MATLAB
)1بدء البرنامج وإنهائه
Starting & Ending MATLAB
لبدء استخدام البرنامج انقر علي أيقونة MATLABللخروج من البرنامج انقر علي أيقونة Exitفي قائمة الملفات.
)2استخدام نافذة الوامر
The Command Window
نافذة الوامر هي النافذة الرئيسية التي من خللها يتم التصال بالمترجم Interpreterوتجرى فيها جميع العمليات الحسابية .يظهر المترجم العلمة (>>) كدليل على جاهز يته لتقبل الوامر .
)3كتابة اسطر الوامر Command Line Editing تحرك إلي اليسار كلمة واحد تحرك إلي بداية السطر
Move left one word
← ctrl
استدعاء السطر السابق
.Recall previous line
↑
Move to beginning of line
home
تحرك إلي نهاية السطر
Move to end of line
end
.Move back one character
←
لحذف السطر
clear line
esc
.Move forward one character
→
لحذف حرف عند المشيرة
delete character at cursor
del
استدعاء السطر قبل السابق تحرك إلي الخلف حرف واحد تحرك إلي المام حرف واحد تحرك إلي اليمين كلمة واحد
Recall next line
↓
Move right one word
→ ctrl
)4مقاطعة البرنامج Interrupting a Running Program يمكن مقاطعة البرنامج في أي لحظة بالضغط على Ctrl-c )5تفويت النتيجة Suppressing Output
عند إدخال البيانات المراد تحليلها والضغط على Enterتظهر النتيجة فوراً على الشاشة .أما إذا أنهيت السطر بشارحة منقوطة فان MATLABيقوم بتحليل البيانات بدون إظهار النتيجة على الشاشة .هذه العملية مفيدة عند إدخال البيانات ذات النتيجة الكبيرة.
)6كتابة الوامر الطويلة
Long Command Lines
إذا كانت المعلومة طويلة بحيث تأخذ اكثر من سطر يمكن استخدام ثلثة نقاط … و Enterلبيان استمرارية المعلومة إلي السطر المقبل .
)7إدخال المصفوفات
ENTERING MATRICES
يجب فصل عناصر الصف الواحد في المصفوفة بواسطة فراغات .كما يجب استخدام فاصلة منقوطة عند نهاية كل صف .وأخيرا يحاط جميع عناصر المصفوفة بواسطة قوسين مربعين ] [ كالتالي: [A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1وبالضغط على المفتاح Enter
عندها يقوم MATLABبإظهار المصفوفة على النحو التالي: =A 13 2 3 8 11 10 12 7 6 1 14 15
16 5 9 4
)8أجراء عملية جمع وقلب المصفوفة
sum, transpose, and diag
لجمع أعمدة المصفوفة نقوم بالعملية التالية)sum )A : لجمع صفوف المصفوفة نأخذ أول مقلوب هذه المصفوفة 'Aثم نجمع أعمدة مقلوب المصفوفة وأخيرا نقلب الناتج كما يلي: ')'sum)A لجمع العناصر القطرية للمصفوفة نقوم بالعملية التالية:
)9التعبيرات الرياضية
))sum)diag)A
mathematical expressions
يحتوي MATLABعلي تعبيرات رياضيةكثيرة وهي :المتغيرات Variables العداد Numbersوالمعاملت او الرموز Operatorsوالدوال Functions
اولً المتغيرات Variablesعندما يكتشف بتخزينه أتوماتيكيا على سبيل المثال إذا كتبت
MATLAB
num_students = 25 فان MATLABيقوم بتخزين يكتب فقط اسم المتغير .num
ثانياً العداد
Numbers
متغير جديد يقوم
هذا المتغير أتوماتيكيا .ولظهاره مرة أخرى يتقبل MATLABالعداد بشكل طبيعي
ثالثاً الرموز الحسابية Addition الجمع+ Subtraction الطرح – Multiplication الضرب * Division / القسمة Left division القسمة اليسارية \ Power ^ الس Complex conjugate transpose المقلوب ' Operators
) (
Specify evaluation order
Functions
رابعاً الدوال الرياضية
.)graph2d )two-dimensional graphs .)graph3d )three-dimensional graphs .)specgraph )specialized graphs .)graphics )handle graphics .)uitools )graphical user interface tools
MATRIX MANIPULATION معالجة الصفوفات .Elementary
matrices
.zeros .ones .eye .repmat
- Zeros array - Ones array - Identity matrix - Replicate and tile array rand - Uniformly distributed random .numbers .Basic array information .size - Size of matrix .length - Length of vector .ndims - Number of dimensions .disp - Display matrix or text .isempty - True for empty matrix
.randn - Normally distributed random numbers .linspace - Linearly spaced vector .logspace - Logarithmically spaced vector .meshgrid - X and Y arrays for 3-D plots .Regularly spaced vector and index into matrix - :
.isequal - True if arrays are identical .isnumeric - True for numeric arrays .islogical - True for logical array .logical - Convert numeric values to logical
.Matrix manipulation .reshape - Change size .diag - Diagonal matrices and diagonals of matrix .tril - Extract lower triangular part .triu - Extract upper triangular part .fliplr - Flip matrix in left/right direction .flipud - Flip matrix in up/down direction
.Special
.flipdim .rot90 .find .end .sub2ind .ind2sub
- Flip matrix along specified dimension - Rotate matrix 90 degrees - Find indices of nonzero elements - Last index - Linear index from multiple subscripts - Multiple subscripts from linear index
.NaN .isnan .isinf .isfinite .flops .why
- Not-a-Number - True for Not-a-Number - True for infinite elements - True for finite elements - Floating point operation count - Succinct answer
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, j - Imaginary unit .inf - Infinity
.Specialized matrices .compan .gallery .hadamard .hankel .hilb .invhilb
- Companion matrix - Higham test matrices - Hadamard matrix - Hankel matrix - Hilbert matrix - 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
.ELEMENTARY MATH FUNCTIONS .Trigonometric .sin - Sine .sinh - Hyperbolic sine .asin - Inverse sine .asinh - Inverse hyperbolic sine .cos - Cosine .cosh - Hyperbolic cosine .acos - Inverse cosine .acosh - Inverse hyperbolic cosine .tan - Tangent .tanh - Hyperbolic tangent .atan - Inverse tangent .atan2 - Four quadrant inverse tangent .atanh - Inverse hyperbolic tangent .Exponential .exp - Exponential .log - Natural logarithm .log10 - Common )base 10( logarithm
.sec .sech .asec .asech .csc .csch .acsc .acsch .cot .coth .acot .acoth
- Secant - Hyperbolic secant - Inverse secant - Inverse hyperbolic secant - Cosecant - Hyperbolic cosecant - Inverse cosecant - Inverse hyperbolic cosecant - Cotangent - Hyperbolic cotangent - Inverse cotangent - Inverse hyperbolic cotangent
.pow2 -Base 2 power and scale floating point number .sqrt - Square root .nextpow2 - Next higher power of 2
.log2 -Base 2 logarithm and dissect floating point number
.Complex
.abs .angle .conj .imag
- Absolute value - Phase angle - Complex conjugate - Complex imaginary part
.Rounding and remainder .fix - Round towards zero .floor - Round towards minus infinity
.real - Complex real part .unwrap - Unwrap phase angle .isreal - True for real array .Cplxpair -Sort numbers into complex conjugate pairs
.ceil .round .)mod
.rem .sign
- Round towards plus infinity - Round towards nearest integer - Modulus )signed remainder after division
- Remainder after division - Signum
.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
.Number theoretic .factor .isprime .primes
.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 .legendre - Associated Legendre function .cross - Vector cross product
functions
- Prime factors - True for prime numbers - Generate list of prime numbers
.gcd .lcm .rat
- Greatest common divisor - Least common multiple - Rational approximation
.rats
- Rational output
.perms
- All possible permutations
.nchoosek -All combinations of N elements taken K at a time
.Coordinate
transforms
.cart2sph -Transform Cartesian to spherical coordinates
hsv2rgb -Convert hue-saturation-value colors to red-green.blue
.cart2pol - Transform Cartesian to polar coordinates .pol2cart - Transform polar to Cartesian coordinates
rgb2hsv - Convert red-green-blue colors to hue.saturation-value
.sph2cart -Transform spherical to Cartesian coordinates
.MATRIX
FUNCTIONS - NUMERICAL LINEAR ALGEBRA
.Matrix analysis .norm - Matrix or vector norm .normest - Estimate the matrix 2-norm .rank - Matrix rank .det - Determinant .trace - Sum of diagonal elements
.null - Null space .orth - Orthogonalization .rref - Reduced row echelon form subspace - Angle between two subspaces
.Linear equations. ."and / .inv
- Linear equation solution; use "help slash \ - Matrix inverse
COND .condest .chol
.cholinc .lu .luinc .qr .nnls .pinv .lscov
- CONDITION NUMBER WITH .RESPECT TO INVERSION - 1-norm condition number estimate - Cholesky factorization
.Matrix functions .expm - Matrix exponential .logm - Matrix logarithm
- Incomplete Cholesky factorization - LU factorization - Incomplete LU factorization - Orthogonal-triangular decomposition - Non-negative least-squares - Pseudoinverse - Least squares with known covariance
.sqrtm .funm
- Matrix square root - Evaluate general matrix function
Factorization utilities .cdf2rdf -Complex diagonal form to real block diagonal form .balance -Diagonal scaling to improve eigenvalue accuracy
.qrdelete - Delete column from QR factorization .qrinsert - Insert column in QR factorization
RSF2CSF -REAL BLOCK DIAGONAL FORM TO .COMPLEX DIAGONAL FORM
.planerot
- Given's plane rotation
.Polynomials .roots - Find polynomial roots .poly - Convert roots to polynomial .polyval - Evaluate polynomial
POLYVALM
- EVALUATE POLYNOMIAL .WITH MATRIX ARGUMENT
.Plotting .ezplot - Easy to use function plotter.
.)residue - Partial-fraction expansion )residues .polyfit - Fit polynomial to data .polyder - Differentiate polynomial .conv - Multiply polynomials .deconv - Divide polynomials
fplot
- Plot function
.Ordinary differential equation solvers ).If unsure about stiffness, try ODE45 first, then ODE15S( .ode45 - Solve non-stiff differential equations, medium order method .ode23 - Solve non-stiff differential equations, low order method .ode113 - Solve non-stiff differential equations, variable order method .ode15s - Solve stiff differential equations, variable order method .ode23s - Solve stiff differential equations, low order method .odefile - ODE file syntax .TWO .Elementary .plot .loglog .semilogx .semilogy
DIMENSIONAL GRAPHS
X-Y graphs
- Linear plot - Log-log scale plot - Semi-log scale plot - Semi-log scale plot
.polar
- Polar coordinate plot
PLOTYY - GRAPHS WITH Y TICK LABELS .ON THE LEFT AND RIGHT
.Axis control .axis - Control axis scaling and appearance .zoom - Zoom in and out on a 2-D plot .grid - Grid lines .subplot - Create axes in tiled positions .Graph annotation .legend - Graph legend .title - Graph title .xlabel - X-axis label
.box .hold .axes
- Axis box - Hold current graph - Create axes in arbitrary positions
.ylabel - Y-axis label .text - Text annotation .gtext - Place text with mouse
.Hardcopy and printing .print - Print graph or SIMULINK system; or save graph to M-file .printopt - Printer defaults .orient - Set paper orientation .Three dimensional graphs .Elementary 3-D plots .plot3 - Plot lines and points in 3-D space .surf - 3-D colored surface .mesh - 3-D mesh surface .fill3 - Filled 3-D polygons .Color control .colormap - Color look-up table .caxis - Pseudocolor axis scaling .shading - Color shading mode
.hidden - Mesh hidden line removal mode .brighten - Brighten or darken color map
.Lighting .surfl - 3-D shaded surface with lighting .lighting - Lighting mode .material - Material reflectance mode .Specialized .Specialized .area .bar .barh .bar3 .bar3h .comet .errorbar .ezplot .feather .fill
.specular - Specular reflectance .diffuse - Diffuse reflectance .surfnorm - Surface normals
graphs
2-D graphs
- Filled area plot - Bar graph - Horizontal bar graph - 3-D bar graph - Horizontal 3-D bar graph - Comet-like trajectory - Error bar plot - Easy to use function plotter - Feather plot - Filled 2-D polygons
.Contour and
.fplot .hist .pareto .pie .pie3 .Plotmatrix .ribbon .stem .stairs
- Plot function - Histogram - Pareto chart - Pie chart - 3-D pie chart - Scatter plot matrix - Draw 2-D lines as ribbons in 3-D - Discrete sequence or "stem" plot - Stairstep plot
2-1/2 D graphs
.contour - Contour plot .contourf - Filled contour plot .contour3 - 3-D Contour plot .clabel - Contour plot elevation labels .Specialized 3-D graphs .comet3 - 3-D comet-like trajectories .meshc - Combination mesh/contour plot .meshz - 3-D mesh with curtain
.pcolor - Pseudocolor )checkerboard( plot .quiver - Quiver plot .voronoi - Voronoi diagram
.stem3 .quiver3 .slice
- 3-D stem plot - 3-D quiver plot - Volumetric slice plot
.surfc .trisurf
- Combination surf/contour plot - Triangular surface plot
.trimesh - Triangular mesh plot .waterfall - Waterfall plot
جمع وطرح المصفوفات Addition and Subtraction 1 1 1 A = 1 2 3 1 3 6
إذا كانت المصفوفة 9 4 C = 2 8 6 7 3 و U = 1 4
لجمع المصفوفتين
و
8 1 6 B = 3 5 7 4 9 2
و
]V = [ 2 0 − 1
,B
Aباستخدام MATLABنقوم بالعملية التالية:
و
X =A+ B
=X 9 4 5
2 7 12
7 10 8
وعند طرح Aمن الناتج نحصل على النتيجة التالية: Y = X –A =Y 8 1 6 3 5 7 4 9 2 w=v+s =w 9 7 6
S =7
و
Vector Products and Transpose ضرب المصفوفات ومقلوبها A row vector and a column vector of the same length can be multiplied in either order. The result is either a scalar, the inner product, or a matrix, the .outer product x = v*u
=x 2 X = u*v =X 3— 0 6 1— 0 2 4— 0 8
Matrix transposition
مقلوب المصفوفة
'X = B =X 438 951 276
'x = v =x 2 0 1— For a complex vector or matrix, z, the quantity z' denotes the complex conjugate transpose. The unconjugated complex transpose is denoted by z.', in analogy with the other array operations. So if
[z = [1+2i 3+4i then z' is
2i—1 4i—3 while z.' is 1+2i 3+4i For complex vectors, the two scalar products x'*y and y'*x are complex conjugates of each other and the scalar product x'*x of a complex vector with .itself is real
Matrix Multiplication
ضرب المصفوفات
The matrix product C = AB is X = A*B
=X 15 15 15 26 38 26 39 70 41 Y = B*A
=Y 47 28 15 60 34 15 43 28 15 A matrix can be multiplied on the right by a column vector and on the left by .a row vector x = A*u
=x 8 17 30 y = v*B =y 10 7— 12
الرسم البياني GRAPHICSباستخدام MATLAB Creating a Plot
اذا كانت yكمية متجهة فان المر )plot)yينتج عنه رسم بياني ل yكدالة في الزمن اما المر )plot)x,yفينتج عنه الرسم البياني yو xمثل ليجاد الرسم البياني للدالة )y = sin)tمن 0الى π 2نجري العملية التالية: ;t = 0:pi/100:2*pi ;)y = sin)t )plot)t,y
;)y2
= sin)t–.25 ;)y3 = sin)t–.5
)plot)t,y,t,y2,t,y3
يمكن رسم كل منحني بلون وخط مميز وذلك باستخدام )'plot)x,y,'color_style_marker :لختيار اللون نختار الحرف التالية .'y', 'r', 'g', 'b', 'w', and 'k')اسود-ابيض-ازرق- اخضر, احمر,( اصفر ) .– : – – –( :لختيار نوع الخط نختار الرموز التالية مثال )'+:plot)x,y,'y
+ سيكون شكل الرسم الناتج هو اصفر منقط به علمة AXIS LABELS AND TITLES
الكتابة علي محور الرسم البياني
The xlabel, ylabel, and zlabel functions add x-, y- and z-axis labels. The title function adds a title at the top of the figure and the text function inserts text .anywhere in the figure
;t = -pi:pi/100:pi ;)y = sin)t )plot)t,y )[axis )[-pi pi -1 1 )'xlabel) '-\pi \leq \itt \leq \pi )')ylabel) 'sin)t )'title )'Graph of the sine function )'{ .text)l -1/3, ' \it{Note the odd symmetry
Mesh and Surface Plots MATLAB defines a surface by the z-coordinates of points above a grid in the x-y plane, using straight lines to connect adjacent points. The functions mesh and surf display surfaces in three dimensions. mesh produces wireframe surfaces that color only the lines connecting the defining points. .surf displays both the connecting lines and the faces of the surface in color
Visualizing Functions of Two Variables To display a function of two variables, z = f )x,y(, generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. Then use these matrices to evaluate and graph the function. The meshgrid function transforms the domain specified by a single vector or two vectors x and y into matrices X and Y for use in evaluating functions of two variables. The rows of X are copies of the vector x and the columns of Y are copies of the vector y. To evaluate the two-dimensional sinc function, :sin)r(/r, between x and y directions
;)X,Y] = meshgrid)–8:.5:8] ;R = sqrt)X.^2 + Y.^2( + eps ;Z = sin)R(./R )mesh)X,Y,Z
In this example, R is the distance from origin, which is at the center of the .matrix .Adding eps avoids the indeterminate 0/0 at the origin
Printing Graphics The Print option on the File menu and the print command both print
.MATLAB figures
MORE ABOUT MATRICES AND ARRAYS This sections shows you more about working with matrices and arrays, focusing on Linear Algebra
• Arrays
• Multivariate Data
•
Linear Algebra Informally, the terms matrix and array are often used interchangeably. More precisely, a matrix is a two-dimensional numeric array that represents a linear transformation. The mathematical operations defined on matrices are the subject of linear algebra. Dürer’s magic square =A 13 2 3 16 8 11 10 5 12 7 6 9 1 14 15 4 provides several examples that give a taste of MATLAB matrix operations. You’ve already seen the matrix transpose, A'. Adding a matrix to its .transpose produces a symmetric matrix 'A + A = ans 17 11 8 32 23 17 20 8 26 14 17 11 2 26 23 17 The multiplication symbol, *, denotes the matrix multiplication involving inner products between rows and columns. Multiplying a matrix by its .transpose also produces a symmetric matrix A'*A = ans 360 206 212 378 206 368 370 212 212 370 368 206 378 212 206 360
PARTIAL-FRACTION EXPANSION WITH MATLAB
MATLAB has a command to obtain the partial-fraction expansion of B(s)/A(s). Consider the transfer function B ) s( num b0 s n + b1s n −1 + .... + bn = = n A) s( den s + a1s n −1 + .... + an
where some of ai and bj may be zero. In MATLAB row vectors num and den specify the coefficients of the numerator and denominator of the transfer ,function. That is
[ num = [b0 b1 ... bn [ den = [1 a1 ….an The command
)r,p,k] =
residue)num,den]
finds the residues, poles, and direct terms of a partial-fraction expansion of .(the ratio of two polynomials B(s) and A(s The partial-fraction expansion of B(s)/A(s) is given by B) s( r )1( r )2( r ) n( = + + .... + + k )s( A) s( s − p )1( s − p )2( s − p ) n(
Comparing this equation with the following B) s( a1 a2 an = + + .... + A) s( s + p1 s + p2 s + pn
we note that p)1( = -p1, p)2( = -p2 ,....... p(n) = -pn; r)1(= a1, r(2) = a2,….. r(n) = an
[.k(s) is a direct term]
:EXAMPLE:
Consider the following transfer function B ) s( 2 s 3 + 5s 2 + 3s + 6 = A) s( s 3 + 6 s 2 + 11s + 6
num = [2 5 3 61 [den = [1 6 11 6 )r;p,k] = residue)num,den] :The command gives the following result )r,p,k] = residue)nurn,den] r= -6.0000 4.00003.0000 p= -3.0000 2.00001.0000= 2k Note that the residues are returned in column vector r, the pole locations in( ).column vector p, and the direct term in row vector k This is the MATLAB B ) s( 2 s 3 + 5s 2 + 3s + 6 −6 −4 3 = 3 = + + +2 2 A) s( s + 6 s + 11s + 6 s + 3 s + 2 s + 1
,(representation of the following partial-fraction expansion of B(s)/A(s The command )num1den]
= residue)r;p,k]
where r, p and k are as given in the previous MATLAB output, converts the :partial-fraction expansion back to the polynomial ratio B(s)/A(s), as follows )num,den] = residue)r,p,k] = num
6.0000 3.0000 5.0000 2.0000 = den 6.0000 11.0000 6.0000 1.0000 Note that if p)j( = p)j + 1( =…..= p)j + m - 1( [that is,pj = pj+1 =…= pj+m-1], the pole p)j( is a pole of multiplicity m. In such a case, the expansion includes terms of the form
)r)j( s - p)j(
+
r)j + 1( +….+ r)j + m - 1 [s -p)j(]2 [s-p)j(]m
EXAMPLE. Expand the following B(s(/A(s( into partial-fractions with .MATLAB
… A)s(
B)s( = s 2 +2s + 3 = s2 + 2s + 3 )s + 1(3 s3 + 3s2 + 3s + 1
For this function, we have
[num = [0 1 2 3 [den = [1 3 3 1 The command )r,p,k] = residue)num,den] .gives the result shown below ;[num = [0 1 2 3 ;[den = [1 3 3 1 )r,p,k] = residue)num,den] =r 1.0000 0.0000 2.0000 =p 1.00001.00001.0000-
=k [] And it is the MATLAB representation of the following partial-fraction :(expansion of B(s)/A(s B) s( 1 0 2 = + + 2 A) s ( s + 1 ) s + 1( ) s + 1(3
.Note that the direct term k is zero Transient response analysis with Matlab
: Consider the system C ) s( 25 = 2 R) s( s + 4s + 25
)1( This system is represented as two arrays each containing the coefficients of the polynomials in decreasing powers of s as follows num = [0 0 251 [den = [1 4 25 Note that zeros are padded where necessary. If num and den )the numerator and denominator of the closed-loop transfer function( are known, commands such as
)step)num,den,t
step)num,den(,
will generate plots of unit-step responses. )t in the step command is the userspecified time.( For a control system defined in a state-space form, where state matrix A, control matrix B, output matrix C, and direct transmission matrix D of state-space equations are known, the command
)step)A,B,C,D will generate plots of unit-step responses. The time vector is automatically determined when t is not explicitly included in the step commands Note that when step commands have left-hand arguments such as
)y,x,t] = step)nun,den,t] )y,x,tl = step)A,B,C,D,iu] )Iy,x,tj = slep)A,B,C,D,iu,t no plot is shown on the screen. Hence it is necessary to use a plot command to see the response curves. The matrices y and x contain the output and state response of the system, respectively, evaluated at the computation time points t. )y has as many columns as outputs and one row for each element in t. x has as many columns as states and one row for each element in t.( Note in Equation )2( that the scalar U is an index into the inputs of the system and specifies which input is to be used for the response. and t is the userspecified time. If the system involves multiple inputs and multiple output the step command, such as given by Equation )4-39(, produces a series of step response plots, one for each input and output combination of x =Ax+Bu y = Cx + Du Obtaining the unit-step response of the transfer-function system. let us consider the unit-step response of the system given by Equation )1(. The .MATLAB Program for this system is
;[num= [0 0 25 ;[den = [1 4 25 )step)num,den grid )')title )'Unit-step Response of G)s(=25/)s^2+4s+25
:A plot of the unit step response curve is shown below
Example :Obtain
the unit-impulse response of the following system x1' 0 1 x1 0 '= x + 1u − 1 − 1 x 2 2 x y = [1 0] 1 + [ 0]u x2
A possible MATLAB program is shown below. The resulting response curve .is also shown below ;[A =
[0 1;-1 -1 ;B = [0;1l ;[C= [1 0 ;[D = [0 ;)impulse)A,B,C,D ;grid )'title)'Unit-Impulse Response
:Example
:
Obtain the unit-impulse response of the following system C )s( 1 = G )s( = 2 R) s( s + 0.2 s + 1
;[num= [0 0 1 ;[den = [1 0.2 1 )impulse)num,den
grid )')title )'Unit- impulse Response of G)s(=1/)s^2+0.2s+1
Example:Consider the impulse response of the standard second-order system defined by ω n2 C ) s( = G )s( = 2 R) s( s + 2ξω n s + ω n
For a unit-impulse input, R(s) = 1. Thus ωn2 ω n2 s 1 C ) s( = 2 = 2 s + 2ξω n s + ω n s + 2ξω n s + ω n s
Consider the normalized system where Wn= 1. Then
C ) s( =
s 1 s 2 + 2ξs + 1 s
Consider five different values of zeta: ξ = 0.1, 0.3, 0.5, 0.7, and 1.0. Obtain .the unit-impulse response curves for each zeta with MATLAB Solution. A MATLAB program for plotting the five unit-impulse response curves in one diagram is
;[Num=[0 1 0 ;[den=[1 0.2 1 ;t=0:0.1:10 ;)step)num,den1,t )'text)2.2,0.88,'zeta=0.1 hold ;[den2= [1 0.6 1]; den3= [1 1 1]; den4= [1 1.4 1]; den5= [1 2 1 ;)step)num,den2,t )'text)1.33,0.72.'0.3 ;)step)num,den3,t )'text)1.15,0.58.'0.5 ;)step)num,den4,t )'text)1.1,0.46.'0.7
;)step)num,den5,t )'text)0.8,0.28.'1.0 grid )'[title)Impulse-responseCurves for G)s(=1/[s^2+2)zeta(s+1 hold
:The resulting diagram is shown below
From the unit-impulse response curves for different values of zeta, we may conclude that if the impulse response c(r) does not change sign the system is either critically damped or overdamped, in which case the corresponding step response does not overshoot, but increases or decreases monotonically .and approaches a constant value
Response To torque disturbances (Proportional control
(
Obtain responses of the above system with MATLAB when it is subjected to .a unit-step disturbance. for a small value of Kp and a large value of Kp :Consider :Case
two cases
l
C )s( 1 = G)s( = 2 D) s( s + 0 .5 s + 1 :Case
:)J=1,
b=0.5, Kp=1 )system 1
2
C ) s( 1 = G ) s( = 2 D) s( s + 0.5s + 4
:)J
= 1, b = 0.5, Kp = 4 )system 2
Note that for system 1 [num1
= [0 0 1 [den1= [1 0. 5 1 For system 2 [num2
= [0 0 1 [den2 = [1 0.5 4 In MATLAB Program we have used notations y1 and y2 for the response. yl .is the response c(t) of system 1, and y2 is the response c(t) of system 2 In MATLAB Program 5-1, note that we have used the plot command with multiple arguments, rather than using the hold command. )We get the same result either way.( To use the plot command with multiple arguments, the sizes of the y1 and y2 vectors need not be the same. However, it is convenient if the two vectors are of the same length. Hence, we specify the same number of computing points by specifying the computing time points )such as t = 0:0.1:20(. The step command must include this user-specified time t. Thus, in MATLAB Program 5-1 we have used the following step :command )y,
x, t] = step)num, den,t]
The unit-step response curves obtained by use of MATLAB Program are .shown below ;[num
1 = [0 0 1 ;[den1 = [1 0.5 1 ;[num2 [0 0 1 ;[den2 [1 0.5 4 ;t = 0:0.1:20 ;)y1,x1,t] = step)num l, den l, t] ;)y2,x2,t] = step)num 2,den2,t] )plot)t,yl,t,y2 grid ' )'text)1 1,0.75,'System 1'(, text )11.2,0.1 6, System 2 )''title)'Step Responses of Two Systems )'xlabel)'t Sec t )'ylalbel) outputs yl and y2
ROOT-LOCUS PLOTS WITH MATLAB
In this section we present the MATLAB approach to the generation of root.locus plots Plotting root loci with MATLAB. In plotting root loci with MATLAB we deal
with the system equation given in the form of 1+ :Which
K ) s + z1 () s + z 2 (....) s + z m ( =0 ) s + p1 () s + p 2 (.....) s + p n (
may be written as 1+ K
num =0 den
Were num is the numerator polynomial and den is the denominator ,polynomial. That is )num
= )s + z1()s +z2 (..... )s + zm s +)z1+z2+….+zm(sm-1+…+z1z2….zm= )den = )s + p1()s+p2( ....... )s + pn sn + )p1 +p2+…. +pn(sn-1 +... +p1 p2 ….pn= m
Note that both vectors num and den must be written in descending powers of s A MATLAB command commonly used for plotting root loci is )rlocus)num,den Using this command, the root-locus plot is drawn on the screen. The gain vector K is automatically determined. The command rlocus works for both continuous- and discrete-time systems. For the systems defined in state space, rlocus)A, B,C, D( plots the root locus of the system with the gain vector automatically determined. Note that commands rlocus)num,den,K( and rlocus)A,B,C,D,K( use the user-supplied gain vector K. )The vector Kcontains all the gain values for which the closed-loop poles are to be computed.( If invoked with left-hand arguments )r,K]
= rlocus)num,den]
)r,K]
= rlocus)num,den,K] )r,KI = rlocus)A,B,C,D] )r,Kl = rlocus)A,B,C,D,K] the screen will show the matrix r and gain vector K. )r has length K rows and length den - 1 columns containing the complex root locations. Each row of the matrix corresponds to a gain from vector K.( The plot command plot)r,' '( plots the root loci. If it is desired to plot the root loci with marks '0'' or 'x', it :is necessary to use the following command )r
= rlocus)num,den )'pIot)r,'x or pIot)r,'o'( EXAMPLE Consider the control system shown below. To plot the rootlocus
diagram with MAT-LAB, it is necessary to find the numerator and .denominator polynomials of the open loop For this problem, the numerator is already given as a polynomial in s. However, the denominator is given as a product of first- and second-order terms, with the result that we must multiply these terms to get a polynomial in S. The multiplication of these terms can be done easily by use of the .convolution command, as shown next Define = s)s +4( = s2 + 4s [b= s+6 2 [c = s + 1.4s + 1 [a
:Then
: a = [1 4 0 : b= [1 6 : c= [1 1.4 1
use the following command
;)d
= conv)a,b )e = conv)c,d [.Note
that conv)a,b( gives the product of two polynomials a and b]
;[a
= [1 4 0 ;[b = [1 6 ;[c = [1 1.4 1 )d = conv)a,b =d 0 24 10 1 )e
= conv)c,d
=e
0 24.0000 43.6000 39.0000 11.4000
1.0000
The denominator polynomial is thus found to be [den
= [1 11.4 39 43.6 24 0
To find the open-loop zeros of the given transfer function, we may use the :following roots command [p
= [1 2 4 )r = roots)p =r 1.7321I + 1.00001.7321I - 1.0000Similarlv, to find the complex-conjugate open-loop poles )the roots of s2 + :1.4s + 1 = 0(, we mav enter the roots commands as follows )q
= roots)c
=q
0.7141i + 0.7141i : The
0.70000.7000-
MATLAB Program will be as shown
;[num
=[0 0 0 1 2 4 ;[den = [1 11.4 39 43.6 24 0 )rlocus)num,den grid )'[)title)'Root-locus Plot of G)s(=K)s^2+2s+4(/[s)s+4()s+6()s^2+1.4s+1
: EXAMPLE
Consider the system shown below, where the open-loop transfer function G(s)H(s) is
G ) s ( H ) s( =
.The
K ) s + 0.2( s 2 ) s + 3.6(
MATLAB Program generates a root-locus plot is as shown
;[num
= [0 0 1 0.2 ;[den = [1 3.6 0 0
)rlocus)num,den )v=
[-4 2 -4 4]; axis)v grid )'[)title)~Root-Locus Plot of G)s( = K)s + 0.2(/[s^2)s + 3.6 The resulting root-locus plot is
EXAMPLE .Consider the system shown
Plot root loci with a square aspect ratio so that a line with slope 1 is a true .450 line To set the plot region on the screen to be square, enter the command axis)'square'(. With this command, a line with slope 1 is at a true 45º, not skewed by the irregular shape of the screen. MATLAB Program which . produces a root-locus plot in a square region is ;[num
= [0 0 0 1 1 ;[3 12 -16 0 den = [1
{rlocus)num,den )61;
axis)v(;axis)'square1 6
-6
v = [-6
grid )'[)title)'Root-Locus Plot of G)s( = K)s + 1 (/[s)s - 1 ()s^2 + 4s + 1 6 . The resulting plot is
: EXAMPLE
Consider the system whose open-loop transfer function G)s(H)s( is G ) s ( H ) s( =
K s ) s + 0.5() s + 0.6 s + 10( 2
=
K s + 1.1s + 10.3s 2 + 5s ( 4
3
There are no open-loop zeros. Open-loop poles are located at 5 = -0.3 + .j3.1480, 5 = -0.3 -j3.1480,s = -0.5~ands = 0 MATLAB Program ;[num=[0
0 0 0 1 ;[den = [1 1.1 10.3 5 0 )rlocus)n urn , den grid
)'[)title)'
Root-Locus Plot of G)s( = K/[s{s + 0.5()s^2 + 0.6s + 10 .the root-locus plot
.Example
: Consider the control system shown
.Plot
root loci with MATLAB .Solution
MATLAB Program ;num
= [0 0 1 0.41
;[den
= [1 3.6 0 0 ;{rlocus)num,den )V = [-5 1 -3 3]; axis)v grid ))'[)title)' Root-Locus Plot of C)s( = K)s + O.4)/[s^2(s + 3.6
PLOTTING BODE DIAGRAMS WITH MATLAB The command bode computes magnitudes and phase angles of the frequency response of continuous-time, linear, time-invariant systems. When the command bode )without left-hand arguments( is entered in the computer, MATLAB produces a Bode plot on the screen. When invoked with left-band arguments, [mag,phase,w] = bode)num,den,w( bode returns the frequency response of the system in matrices mag, phase and w- No plot is drawn on the screen-The matrices mag and phase contain magnitudes and phase angles of the frequency response of the system evaluated at user specified frequency points. The phase angle is returned in degrees. The magnitude can be converted to decibels with the statement magdB = 20*Iogl0)mag( To specify the frequency range, use the command Iogspace)d1 ,d2( or Iogspace )d1 ,d2,n(. logspace)dl ,d2( generates a vector of 50 points logarithmically
equally spaced between decades 10d1 and 10d2. That is, to generate 50 points .)between 0.1 rad/sec and100 rad/sec, enter the command w = logspace)-1,2 logspace)d1 ,d2,n( generates n points logarithmically equally spaced between decades 10d1 and 10d2 For example, to generate100 points between 1 rad/sec and 1000 rad/sec, enter the following command: w = Iogspace)0,3,100( To incorporate these frequency points when plotting Bode diagrams, use the command bode)num,den,w( or bode)A,B,C,D,iu,w(.These .commands use the user-specified frequency vector w :Example1 :Consider
the following transfer function G)s( =
25 s + 4 s + 25 2
Plot a Bode diagram for this transfer function. When the system is defined in the form )G(s)
=
den)s(, num)s
use the command bode)num,den( to draw the Bode diagram. [when the numerator and denominator contain the polynomial coefficients in descending powers of s, bode)num,den( draws the Bode diagram.] .MATLAB Program to plot the Bode diagram for this system is )num
[0 0 25 ,[den [1 4 25 )bode)num,den [subplot[2 1 1 )')title)' Bode Diagram of G)s(=25/)s^2+4s+25 .The
resulting Bode diagram is
:Example
2 :Plot a bode diagram for a system with the open-loop transfer function of 9) s 2 + 0.2 s + 1( G)s( = s) s 2 + 1.2 s + 9( .MATLAB
Program
[num
= [0 9 1.8 9 ;[den =[1 1.2 9 0 )bode)num,den ;)subpIot)2,1,1 ) )'[)title)'Bode Diagram of G)s( = 9)s^2 + 0.2s+1(/[s)s^2+1.2s + 9 .The
resulting plot is
The frequency range in this case is automatically determined to be from 0.1 to 10 rad/sec. If it is desired to plot the Bode diagram from 0.1 to 1000 rad/sec, enter the following command; w = logspace)-2,3,100( This command generates 100 points logrithmically equally spaced between 0.01 and 100 rad/sec. )Note that such a vector w specifies the frequencies in radians per sccond at which the frequency response will be calculated.( If we use the command bode)num,den,w( then the frequency range is as user specified, but the magnitude range and phase-angle range will be .automatically determined
Obtaining Bode diagrams of systems defined in state space
.
Consider the system defined by X' = Ax + Bu y = Cx + Du where )x = state vector )n-vector )y = output vector )m-vector )u = control vector )r-vector )A = state matrix (n x n matrix )B = control matrix (n x r matrix
)C
= output matrix (m x n matrix )D = direct transmission matrix (m x r matrix A Bode diagram for this system may be obtained by entering the command )bode)A,B,C,D(
or
bode)A,B,C,D,iu
The command bode)A,B,C,D( produces a series of Bode plots, one for each input of the system, with the frequency range automatically determined. )More points are used when the response is changing rapidly.( The command bode)A, B,C,D,iu( where iu is the ith input of the system, produces the Bode diagrams from the input iu to all the outputs )y1, y2,---, ym) of the system, with frequency range automatically determined. )The scalar iu is an index into the inputs of the system and specifies which input is to be used for plotting Bode diagrams(. If the control vector u has three inputs such that u1 u = u 2 u 3
then iu must be set to either 1,2, or 3. If the system has only one input u,then :either of the following commands may be used )bode)A,B,C,D( or bode)A,B,C,D,1 :Example
3: Consider the following system
x1' 0 1 x1 0 '= + u x 2 − 25 − 4 x 2 25 x y = [1 0] 1 x2
This system has one input u and one output y. Then the MATLAB Program :is ;[A =
[0 1; -25 -4 ;[B = [0;25 ;[C = [1 0
;[D
= [0 )Bode)A,B,C,D ;)Subplot)2,1,1 )'Title)'Bode Diagram :we
obtain the Bode diagram shown as shown below
If we replace the command bode)A,B,C,D( in MATLAB Program with )bode)A,B,C,D,1 .then MATLAB will produce the Bode diagram identical to that shown above