Lab 1-Introduction to MATLAB
- 格式:doc
- 大小:514.50 KB
- 文档页数:11
Engineering Circuit Analysis Eighth Edition Course Design IntroductionThe purpose of this course design is to guide students in understanding circuit analysis principles using the Engineering Circuit Analysis Eighth Edition textbook by William H. Hayt, Jack E. Kemmerly, and Steven M. Durbin.The course is assumed to be taught in an academic setting with students having a basic understanding of circuitanalysis concepts. The length of the course is 16 weeks with three hours of class per week and an additional hour for laboratory experiments.Learning OutcomesBy the end of this course, students should be able to: •Apply circuit analysis principles to analyze DC and AC circuits•Analyze the behavior of active circuits such as amplifiers and oscillators•Understand LTI (linear time-invariant) systems and their response to different input signals•Analyze circuits using Laplace transform and frequency domn techniques•Use MATLAB to solve circuit analysis problems and simulate circuitsCourse ContentWeek 1-2: Introduction and DC Circuit Analysis•Course introduction, syllabus review•Voltage, current, resistance, power, Ohm’s law•Kirchhoff’s laws, nodal and mesh analysis•Circuit theorems: superposition, Thevenin’s and Norton’s theorems•Applications: voltage and current dividers, Wheatstone bridgeWeek 3-4: Capacitors and Inductors•Capacitance, charge and energy stored in capacitors •Inductance, flux and energy stored in inductors•Series and parallel combinations of capacitors and inductors•Time domn analysis of RC and RL circuits•Transient analysis of first-order circuitsWeek 5-6: AC Circuit Analysis•AC circuits, phasors and complex numbers•Circuit analysis using phasors•Reactance, impedance and admittance•Applications: filters, resonance, transformers Week 7-8: LTI Systems and Frequency Domn Analysis •LTI systems: impulse response, step response, transfer function•Fourier series and Fourier transform•Frequency response: Bode plots, frequency domn analysis•Filters: low-pass, high-pass, band-pass, band-stop Week 9-10: Amplifiers•Basics of amplifiers, types of amplifiers•Amplifier characteristics: gn, input and output resistances, bandwidth•BJT amplifiers: biasing, small-signal models, analysis using hybrid-pi model•FET amplifiers: biasing, small-signal models, analysis using T-model•Applications: differential amplifiers, operational amplifiersWeek 11-12: Oscillators•Basics of oscillators, feedback concept•Conditions for oscillation, types of oscillators •Analysis of LC oscillator•Analysis of crystal oscillator•Frequency stability and feedback compensation Week 13-14: Laplace Transform•Introduction to Laplace transform•Laplace transform properties•Circuit analysis using Laplace transform•Inverse Laplace transform•Applications: circuit analysis of second-order circuits.Week 15-16: MATLAB•Introduction to MATLAB•Numeric computation using MATLAB•Symbolic computation using MATLAB•Circuit analysis using MATLAB•Laboratory experiments.AssessmentThe course will be assessed through a combination of homework assignments, quizzes, laboratory experiments, and a final examination. The weightage for each component is as follows:•Homework assignments: 20%•Quizzes: 20%•Laboratory experiments: 20%•Final examination: 40%ConclusionThis course design is intended to provide a comprehensive understanding of circuit analysis principles using the Engineering Circuit Analysis Eighth Edition textbook. It is expected to equip students with the skills to analyze and design circuits using both time domn and frequency domn techniques. The laboratory experiments and MATLAB assignments will help students to develop practical skills for circuit analysis.。
第一篇MATLAB入门第1章MATLAB简介MATLAB(Matrix Laboratory)是由MathWorks公司于1984年推出的一套科学计算软件,分为总包和若干个工具箱。
它具有强大的矩阵计算和数据可视化能力。
1.1 MATLAB的主要特点该软件的主要特点:⑴简单易学:MATLAB是一门编程语言,其语法规则与一般的结构化高级编程语言大同小异,而且使用更方便,具有一般语言基础的用户很快就可以掌握。
⑵代码短小高效:由于MATLAB已经将数学问题的具体算法编成了现成的函数,用户只要熟悉算法的特点、使用场合、函数的调用格式和参数意义等,通过调用函数很快就可以解决问题,而不必花大量的时间纠缠于具体算法的实现。
⑶计算功能非常强大:该软件具有强大的矩阵计算功能,利用一般的符号和函数就可以对矩阵进行加、减、乘、除运算以及转置和求逆等运算,而且可以处理稀疏矩阵等特殊的矩阵,非常适合于有限元等大型数值算法的编程。
此外,该软件现有的数十个工具箱,可以解决应用中的很多数学问题。
⑷强大的图形绘制和处理功能:该软件可以绘制常见的二维三维图形,还可以对三维图形进行颜色、光照、材质、纹理和透明性设置并进行交互处理。
⑸可扩展性能:可扩展性能是该软件的一大优点,用户可以自己编写M文件,组成自己的工具箱,方便地解决本领域内常见的计算问题。
此外,利用MATLAB编译器可以生成独立的可执行程序,从而可以隐藏算法并避免依赖MATLAB。
1.2 MATLAB桌面简介启动MATLAB时,MA TLAB的桌面如图1-1。
可以根据需要改变桌面外观,包括移动、缩放和关闭工具窗口等。
MATLAB桌面包括表1-1中的几种工具窗口,在默认情况下,它们中间有一些没有显示。
1.2.1 启动按钮(“Start”)打开MATLAB主界面以后,单击“Start”按钮,显示一个菜单,利用“Start”菜单及其子菜单中的选项,可以直接打开MA TLAB的有关工具。
MATLAB编程基础入门教程Chapter 1: Introduction to MATLAB ProgrammingMATLAB is a widely used programming language and environment that is specifically designed for numerical computing. In this chapter, we will provide a comprehensive introduction to MATLAB programming and its fundamental concepts.1.1 MATLAB EnvironmentMATLAB provides an interactive environment where users can write and execute their programs. It offers a user-friendly interface that includes a command window, an editor, and a workspace. The command window allows users to execute commands directly and see the output instantly. The editor is used to write and save MATLAB programs, while the workspace displays the variables and their values.1.2 Variables and Data TypesIn MATLAB, variables are used to store data. They can be assigned values of different data types, including numeric data types such as integers, floating-point numbers, and complex numbers. MATLAB also supports character and string data types. Understanding data types is crucial for performing accurate calculations and data manipulations.1.3 Basic OperationsMATLAB supports a wide range of arithmetic and logical operations. Users can perform basic operations such as addition,subtraction, multiplication, and division on both scalars and arrays. MATLAB also provides functions for more complex mathematical operations such as exponentiation, logarithm, and trigonometric functions.1.4 Control Flow StatementsControl flow statements allow users to control the flow of program execution. MATLAB supports various control flow statements, including if-else statements, for loops, while loops, and switch statements. These statements enable users to write programs that can make decisions or repeat steps based on certain conditions.Chapter 2: MATLAB Programming TechniquesIn this chapter, we will delve deeper into MATLAB programming techniques that will enhance the efficiency and readability of your code.2.1 Functions and ScriptsFunctions and scripts are two fundamental components of MATLAB programming. Functions are reusable pieces of code that accept inputs and produce outputs. They allow for modular and organized programming. Scripts, on the other hand, are collections of code that execute in a specific order. They are useful for automating a series of commands or calculations.2.2 File I/O OperationsMATLAB provides functions to read and write data from and to different file formats. These file I/O operations are crucial for data analysis and processing tasks. MATLAB supports file formats such as text files, spreadsheets, images, and audio files. Understanding how to efficiently read and write data from different file formats will greatly enhance your data processing capabilities.2.3 Error HandlingError handling is an essential aspect of programming. MATLAB provides mechanisms to catch and handle errors that may occur during program execution. By implementing proper error handling techniques, you can make your code more robust and prevent unexpected crashes or undesired outcomes.2.4 Debugging and ProfilingDebugging is the process of identifying and fixing errors or bugs in your code. MATLAB provides debugging tools that allow you to step through your code, set breakpoints, and inspect variables. Profiling, on the other hand, helps identify code bottlenecks and optimize the performance of your programs. Profiling tools provide insights into the execution time and memory usage of different parts of your code.Chapter 3: MATLAB Graphics and VisualizationMATLAB offers powerful tools for creating highly visual and interactive graphics. In this chapter, we will explore MATLAB'sgraphics capabilities and techniques for creating professional-quality visualizations.3.1 Basic PlottingMATLAB provides functions for creating basic 2D and 3D plots. Users can plot data points, lines, surfaces, and volumes. They can also customize the appearance of plots by changing colors, line styles, and markers. Understanding how to create and customize basic plots will enable you to effectively visualize your data.3.2 Advanced Plotting TechniquesMATLAB's advanced plotting techniques allow users to create more complex visualizations. These techniques include plotting multiple data sets on the same graph, adding legends and labels, creating subplots, and customizing axes properties. By mastering these techniques, you can generate informative and aesthetically pleasing visualizations.3.3 Animation and Interactive GraphicsMATLAB provides tools for creating animations and interactive graphics. Animation allows you to visualize changes in data over time. Interactive graphics enable users to interact with plots by zooming, panning, or selecting data points. Understanding how to create animations and interactive graphics will enhance the engagement and effectiveness of your visualizations.Chapter 4: MATLAB Applications and ExtensionsMATLAB offers a wide range of toolboxes and extensions that extend its functionality and allow users to solve specific technical problems. In this chapter, we will explore some popular MATLAB toolboxes and their applications.4.1 Signal Processing ToolboxThe Signal Processing Toolbox provides functions for analyzing and processing signals. It offers tools for filtering, spectral analysis, time-frequency analysis, and wavelet analysis. This toolbox is widely used in fields such as telecommunications, audio processing, and biomedical engineering.4.2 Image Processing ToolboxThe Image Processing Toolbox is designed for image analysis and manipulation tasks. It offers functions for image enhancement, segmentation, morphological operations, and spatial transformations. This toolbox finds applications in fields such as medical imaging, computer vision, and remote sensing.4.3 Control System ToolboxThe Control System Toolbox provides tools for analyzing and designing control systems. It offers functions for modeling, simulation, and control system design. This toolbox is valuable for engineers working in fields such as robotics, aerospace, and industrial automation.4.4 Machine Learning ToolboxThe Machine Learning Toolbox enables users to implement various machine learning algorithms. It provides functions for classification, regression, clustering, and dimensionality reduction. This toolbox is widely used in data analysis, pattern recognition, and predictive modeling.Conclusion:MATLAB is a powerful and versatile programming language for numerical computing. In this tutorial, we have covered the essential concepts and techniques required for getting started with MATLAB programming. By mastering these foundation skills, you can explore more advanced topics and unlock the full potential of MATLAB as a tool for technical computation and data visualization.。
Introduc)on t o M ATLABMATLAB简介及入门Lecture O utline•The M ATLAB E nvironment (IDE)–Workspace a nd F ile s ystems (m-‐files, m at-‐file, m ex-‐file) •MATLAB B asics–Variables, O perators, B uilt-‐in f unc)ons•Flow C ontrol•PloVng•Efficiency: T hinking i n M ATLAB•Concluding R emarksMATLAB•Stands f or M ATrix L ABoratory•Interpreted l anguage (直译语言)•Scien)fic p rogramming e nvironment•Very g ood t ool f or t he m anipula)on o f m atrices •Excellent v isualiza)on c apabili)es•Loads o f b uilt-‐in f unc)ons•Easy t o l earn a nd s imple t o u seMATLAB•How t o g et i t?–Download f rom M athworks w ebsite•Pricing a nd L icensing–MATLAB 30-‐Day F ree T rial–O^en p rovided b y y our i ns)tute–Affordable s tudent l icenseCost o f s tudent l icense i n S witzerlandThe M ATLAB E nvironment (IDE)File S ystems•m-‐files–Code s cripts/User-‐defined f unc)ons•mat-‐files–Data/variable s torage•mex-‐files–Callable f unc)ons b uilt f rom C/C++, o r F ortranMATLAB B asics•Variables (变量)–Type, N aming, A ssignment•Operators (操作符)–Arithme)c/Matrix/Element-‐wise/Logic o pera)ons •Built-‐in f unc)ons (内建函数)•Variable t ypes–Numeric/Logical–Character a nd s tring–Cell a nd S tructure–Table–All n umeric v ariables c an b e c onsidered a svectors/matrices/high-‐dimensional a rray–The s calar v ariables a re 1x1 m atrices w ithdouble p recision u nless s pecified •Case s ensi)ve (X i s n ot e qual t o x!)•Variable n ames m ust s tart w ith a l ejerArray, M atrix•a v ector x = [1 2 5 1] x =1 2 5 1 •transpose y = x’y =1251 •a m atrix x = [12 3; 5 1 4;3 2 -1] x =1 2 35 1 43 2 -1Array, M atrix•t =1:10t =1 2 3 4 5 6 7 8 9 10 • k =2:-0.5:-1k =2 1.5 1 0.5 0 -0.5 -1•x = [1:4; 5:8]x =1 2 3 45 6 7 8Genera)ng M atrices f rom F unc)ons •zeros(M,N) M xN m atrix o f z eros •ones(M,N) M xN m atrix o f o nes•rand(M,N) M xN m atrix o f u niformly d istributed r andom n umbers o n (0,1)x = zeros(1,3)x =0 0 0x = ones(1,3)x =1 1 1 x = rand(1,3) x = 0.9501 0.2311 0.6068Matrix I ndex•The m atrix i ndices b egin f rom 1 (not 0 (as i n C )) •The m atrix i ndices m ust b e p osi)ve i ntegerA(-‐2), A (0) Error: ??? S ubscript i ndices m ust e ither b e r eal p osi)ve i ntegers o r l ogicals. A(4,2) Error: ??? I ndex e xceeds m atrix d imensions.Concatena)on o f M atrices •x = [1 2], y = [4 5], z=[ 0 0]• A = [ x y]1 2 4 5•B = [x; y]1 24 5 C = [x y ;z] Error: ??? E rror u sing ==> v ertcat C AT a rguments d imensions a re n ot c onsistent.Variables N aming T ricks•Don’t n ame y our v ariables t he s ame a s (built-‐in) f unc)ons –min, m ax, s qrt, c os, s in, t an, m ean, m edian, e tc–Otherwise y ou w ill n ot b e a ble t o u se t hese f unc)ons.•MATLAB r eserved w ords d on’t w ork e ither–i, j, e ps, n argin, e nd, p i, d ate, e tc–i, j a re r eserved a s c omplex n umbers i ni)ally•Will w ork a s c ounters i n m y e xperience s o t hey c an b e r edefined a s r ealnumbers. B ut I s uggest u sing i i o r j j i nstead.Arithme)c O perators •Scalar a rithme)c o pera)onsO pera)on M ATLAB f orm–Exponen)a)on: ^ a b a^b–Mul)plica)on: * a b a*b–Right D ivision: / a / b = a/b a/b–Addi)on: + a + b a+b–Subtrac)on: -‐ a – b a-‐b•MATLAB i gnores w hite s pace b etween v ariables a nd o peratorsMatrix O pera)onsGiven A a nd B:Addi)on Subtrac)on Product TransposeElement-‐wise O pera)onsK= x ^2 ??? E rror u sing ==> m power M atrix m ust b e s quare. B=x*y ??? E rror u sing ==> m )mes I nner m atrix d imensions m ust a gree. A = [1 2 3; 5 1 4; 3 2 1] A = 1 2 3 5 1 4 3 2 -‐1y = A (3 ,:) y= 3 4 -‐1 b = x .* y b= 3 8 -‐3 c = x . / y c= 0.33 0.5 -‐3 d = x .^2 d= 1 4 9 x = A (1,:) x= 1 2 3 .* e lement-‐by-‐element m ul)plica)on ./ e lement-‐by-‐element d ivision .^ e lement-‐by-‐element p owerOrder o f O pera)ons•Parentheses•Exponen)a)on•Mul)plica)on a nd d ivision h ave e qual p recedence •Addi)on a nd s ubtrac)on h ave e qual p recedence •Evalua)on o ccurs f rom l e^ t o r ight•When i n d oubt, u se p arentheses–MATLAB w ill h elp m atch p arentheses f or y ouLogical O pera)onsExample: G et a b inaryversion o f a m atrixBuilt-‐in F unc)ons •Mathema)cal e xpressions–sqrt, l og, e xp, ...•Sta)s)cs–sum, m in, m ax, s td, ...•Element s earch–find, i smember, u nique, ...•And m any o thers!–Always s earch t he d ocumenta)on b efore y ou i mplement y our own f unc)ons!Flow C ontrol •if•for•while•break•….•If S tatement S yntaxif (Condi)on_1)M atlab C ommands elseif (Condi)on_2)M atlab C ommandselseM atlab C ommandsendif ((a>3) & (b==5))Some Matlab Commands; endif (a<3)Some Matlab Commands; elseif (b~=5)Some Matlab Commands; endif (a<3)Some Matlab Commands; elseSome Matlab Commands; end•For l oop s yntaxfor i i=Index_ArrayM atlab C ommands endfor ii=1:100Some Matlab Commands; Endfor jj=1:3:200Some Matlab Commands; endfor m=13:-0.2:-21Some Matlab Commands; endfor k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands; end•While L oop S yntaxwhile (condi)on)M atlab C ommands end while ((a>3) & (b==5))Some Matlab Commands; EndPloVng•Basic 2D p lot–plot, b ar, s cajer, s tem ...•Basic 3D p lot–surf, m esh, ...•Figure P roper)es–LineSpec, x label, y label, l egend, a nd s et g ca f or m ore p lot proper)eson xcomparisonDistribu)onEfficiency: T hinking i n M ATLAB•Interpreted l anguages a re o^en s low i n e xecu)on •But, t he efficiency c an b e s ignificantly i mproved i f you w rite y our c ode p roperly.Thinking i n M ATLAB:F ormulate y our p roblem a s m atrix o pera1ons!14x 1me f aster !!!Scajer P lotConcluding R emarks •MATLAB: A p owerful d ata a nalysis t ool •Rich b uilt-‐in f unc)ons a nd t oolbox•Very s trong d ata m anipula)on a bility •Excellent d ata v isualiza)on•Big d ata s upport: D istributed c ompu)ng p ool •Comparison w ith o ther d ata a naly)c t ools •How t o l earn M ATLAB b y y ourself ?Comparison w ith O ther D ata A naly)c T oolsSource: N YU D ata S ervicesMATLAB H elp•Product h elp w indow–Help>product h elpMATLAB O nline D ocumenta)on •Reference t o a ll t he f unc)ons•Rich e xamples a nd t utorialsMATLAB C entral•Online u ser c ommunity•Rich q ues)on/answer a nd c ode e xchanges。
G ETTING STARTED WITH M ATLAB AND S IMULINKIntroduction to MATLABMATLAB is an interactive program useful for scientific and engineering calculations. MATLAB belongs to the Mathworks () family of products. Along with MATLAB and SIMULINK Mathworks also offer numerous add-ons, which extended the functionality of MATLAB/SIMULINK. These add-ons are called toolboxes/blocksets. SIMULINK is an easy to use graphical package suitable for simulating continuous and discrete-time dynamical systems. It is possible to use SIMULINK with almost no knowledge of MATLAB, however in-order to get the most out of the package one needs to have a basic understanding of MATLAB.Starting MATLABStart MATLAB by double-clicking on the MATLAB icon in the Windows environment. After MATLAB has loaded, a double arrow prompt ( >> ) will appear in the MATLAB workspace window. At the beginning of each MATLAB session it is important to first move to your working directory. For example, if your working directory is your home directory on the H: drive then type:cd h:Alternatively, follow the instructions given in the figure below. Typing ‘cd’ on its own displays the current working directory.It is important to type all commands in lower case as MATLAB is case sensitive.Variables and Mathematical OperationsAll MATLAB variables are matrices. Variable names can be up to 19 characters in length. The first character must be a letter, but all remaining characters can be anyletter or number. Variable names in MATLAB are case sensitive meaning that “M”and “m” are not the same. MATLAB uses the assignment so that equals (“=”) implies the assignment of the expression to the variable. Thus>>variable=expressionIf we wished to assign the value 5 to a variable called “A” we would typeA=5 <enter>The statement is executed after the enter key is pressed. If the statement is followedby a semicolon (;), the output is suppressed (not displayed on screen). The assignment of the variable is carried out even though the output is suppressed by the semicolon. A complete list of the current defined variables can be obtained with the command “whos”.MATLAB is equipped with many useful functions some of which are given hereOperation Function Operation Functionsin(x), cos(x) Sine/cosine of variable x. min(x) Minimum value of x.asin(x), acos(x) Inverse sine/cosine of x.max(x) Maximum value of x.x.mean(x) Average value of x.ofsqrt(x) Squarerootabs(x) Absolute value of x.round(x) Round towards integer.x. fix(x) Round towards 0.ofinv(x) InverseUseful CommandsCommand Function whos Lists variables currently in workspace.clear Clears all variables from the workspace.clear x, y, z Clears variables x, y and z from the workspaceclear all Clears all variables and functions from the workspace.clc Clear the command window.close Closes figure window.Help topic Provides help on topic.flops Show the number of floating point operations used so far.Generating PlotsPlotting with MATLAB is easy and there are numerous types of graph one can plot. For the purpose of the work carried out in this module the two most important types of graph are the single (x, y) graph and figures containing multiple (x, y) graphs. The best way to illustrate the plotting capabilities of MATLAB is via an example but before we do so it is important to introduce the notion of colon notation.a=[xs:dx:xf];The colon notation allows us to generate a row of vectors containing numbers from a given starting value, xs, to a final value, xf, with a specified increment, dx. Suppose our objective is to generate a plot of f(x) = sin(x) versus x for x = 0,0.1,0.2…,2π. Our first step is to generate a table x of data. We can generate a vector containing the values of x at which the values of y(x) are desired using the colon notation, as x=[0:0.1:2*pi];Once we have our data we can plot y=sin(x) versus x usingplot(x,sin(x))Notice the coma between x and sin(x). Furthermore we can add a title to our graph and label the x-axis and y-axistitle(‘Plot of sin(x) versus x’)xlabel(‘Angle (radians)’)ylabel(‘f(x)’)For more details about using plot type: help plot at the MATLAB prompt.TASK 1. Plotting simple functionsMATLAB plots can be copied to the Clipboard where they can be subsequently pasted into a Word document. For MATLAB plots, pull down the ‘Edit’ menu. Set the ‘Copy Options’ to Windows Metafile, then select ‘Copy Figure’ to place the diagram in the Clipboard.It is possible to plot multiple functions on the same graph either by including more than one set of (x, y) values in the plot function or using the “hold on” command. For example suppose we wanted to plot the function f(x) = sin(2x) and its derivative on the same plotx=[0:0.1:2*pi];y1=sin(2*x);y2=2*cos(2*x);plot(x,y1,x,y2);Lets say we want to distinguish between the two functions, we can the change the line colour and the marker style by changing the plot command thusplot(x,y1,’r--‘,x,y2,’k’)We can also add a legend as followsLegend(‘sin(2x)’,’2cos(2x)’)The resulting plot copied and pasted to word is shown belowAngle (radians)yPlot of sin(x) and its derivative v ersus xAlternatively we can use the “hold on ” command thus plot(x,y1,’r--‘)holdonplot(x,y2,’k’)Finally another useful type of plot involves splitting the graph display into smaller sub-windows. The function “subplot(m,n,p)” divides the graph display into an m by n grid of smaller sub-windows. The integer p specifies the window numbered left to right top to bottom (if splitting the graph into 4 sub plots). For further assistance using subplot type: help subplot at the MATLAB prompt.Subplot(2,1,1)Subplot(2,1,2)Programming MATLAB (m-files)Although the MATLAB examples so far are presented as lines typed into the command window, it is possible (and often prudent, if repetition as an issue) to write a program so that calculations are more convenient. This is accomplished in MATLAB by writing an m-file. This is simply a text file saved with a “.m” extension. We pull down the New M-File under the File menu, which opens up the m-file editor (note that you can use another text editor such as notepad if you prefer.) When the program is written we save it in an appropriate directory, then close the editor. We can run the program by re-opening it and pressing f5 or we can right click on the program m-file in the current directory and chose Run from the listed options.TASK 2. A simple programLets write a small program that allows the user to select the magnitude and frequencyof a sine wave and plot the results.Save the m-file to your working directory and run the program. MATLAB will prompt you for the amplitude and frequency of the sine wave. Entering 3 and 5 respectively will produce the following plot.Time (s)V o l t a g e (V )Voltage against timeTASK 3. Determinate repetition using the “for” loopLooping statements, or loops, allow other statements to be repeated. There are two basic kinds of loops Determinate and Indeterminate. A determinate loop is one that repeats statements a specified number of times. The indeterminate loop will be discussed in task 4. The “for” statement, or the “for” loop, is a determinate loop. The general form of the loop is:for loopvar=rangeactionendLet’s use a for loop to calculate and plot induction machine rotor current against percentage of synchronous speed:TASK 4. Indeterminate repetition using the “while” loopWhen it’s not possible to know, beforehand, the number of repetitions required in a program the “for” loop cannot be used. One useful looping function is the “while” statement. The general form of the “while” statement is given below:while conditionstatementsendHere is a fun example for you to try out:The operation of the program should be self explanatory.Introduction to SIMULINKSIMULINK models are created by drawing the system diagram in a block diagram window using special blocks supplied with the package. Once built, the system model can be simulated by choosing appropriate menu options from the system block diagram window, or by entering commands in the MATLAB command window. The progress of a simulation can be viewed while the simulation is running, using special scope blocks in the system diagram. The final results can be made available in the MATLAB work space when the simulation is complete and can then be further analysed using any of the MATLAB functions. There are two ways to initiate a SIMULINK session:1. Click on the SIMULINK icon on the MATLAB toolbar.2. Enter the simulink(lower case) command at the command prompt.Enter Simulink command atthe command prompt.Click here tostart Simulink.MATLAB toolbar.Starting SIMULINK will display the SIMULINK Library Browser. To create a new model, click the ‘New’ button on the Library Browser’s toolbar. To open a previously saved SIMULINK model, select the ‘Open’ button from the Library Browser’s toolbar. Then select the filename of the model you wish to open (Note: all model files have an extension ‘.mdl’).TASK 5. Building a SIMULINK modelBy far the easiest and fastest way to learn how to use SIMLINK is to use it! Here we will create a simple SIMULINK model, which creates three sine waves each having different amplitudes and frequencies. The sine wave are then summed and a graph showing all of the signals is plotted using a scope block and a to Workspace block The scope block allows you to view the simulation results as the simulation is running while the Workspace block allows you to plot and manipulate the results using an appropriate MATLAB function of your choosing. For this simulation you will need three Sine wave blocks a Sum block and a Scope block. These blocks can be found in the Source, Math and Sinks libraries respectively. The first stage is to place all required blocks in the new model window. The individual settings for each block are made in a later section.Blocks are added to the new window by dragging blocks from the Library Browser window using the mouse. In the Library Browser blocks are grouped together, e.g. Sinks, Continuous, etc. Blocks in the new model window can be cut, copied and pasted within the window by selecting a block with the mouse and selecting appropriate options from the ‘Edit’ menu or toolbar. Blocks can be moved by selecting and dragging with the mouse. Blocks can be resized by selecting the block,then clicking and dragging a block corner. Create a new model for simulation, drag and drop the required blocks and connect them as show below. In order to plot the signals using MATALB you will also need a Clock block and To workspace blocks.Each block has its own settings which are changed to configure the model for the specific simulation under investigation. Block settings are viewed and altered by double clicking on a block which opens a dialogue window. Additional help with each block is available by clicking the ‘Help’ button in the block dialogue window. Some block settings are also shown in the SIMULINK diagram, e.g. the variable name in the To Workspace block. The settings for each block in the example are discussed in the following sections.To Workspace block (sinks)The To Workplace block enables results from a simulation to be available in the MATLAB workspace after the simulation is completed. The dialogue window for this block has several boxes. Default values are usually good except for:Variable name: Enter the name of the variable that will be used to store this data in the MATLAB workspace. (default = simout)Save format: Set this to ‘Array’ format (default = ‘structure’).For the example there are 3 To Workspace blocks. Change the variable names in these blocks to be t, sig1 and sig2 as shown in the figure. Also limit the number of data points to the last 10000.Sine Wave block (sources)As the name implies this block generates a sine wave at the output. Double click this block and set the following parameters.Block name Amplitude FrequencySine Wave 1 10*2*piSine Wave1 1/3 30*2*piSine Wave2 1/5 50*2*piThe remaining parameters should remain as the default values. Once again for further information use the help feature.Scope block (sinks)The scope block plots the response of the line it is connected to as the simulation is running. It behaves rather like an oscilloscope and is opened by double-clicking. ‘Autoscale’ is very useful after the simulation has run. Set up the Scope block as shown below.1. Double click to2. Click here to openopenscope parameters 3. Change number ofaxis4. Click here and unchecklimit dataSaving the ModelAt this stage it might be wise to save the model so that it is not lost if something were to go wrong during the simulation stage. To save a model, select ‘Save As’ from the ‘File’ menu of the model window, enter a filename (sim1) and select ‘OK’. The saved model will have an extension ‘.mdl’. Subsequent saves under the same filename can be made by selecting ‘Save’ from the ‘File’ menu or toolbar.Simulating the ModelSimulation of a dynamic model involves the numerical integration of sets of ordinary differential equations. SIMULINK provides a number of integration algorithms for the simulation of such equations. Unfortunately, due to the diversity of dynamical system behaviour, no single method is guaranteed to simulate every type of model accurately and efficiently. The appropriate choice of method and the careful selection of simulation parameters are important considerations for obtaining accurate results. The default ode4 (Runge-Kutta fifth-order) integration algorithm is highly recommended due to its relatively good performance for a wide variety of systems, including linear, non-linear and discontinuous systems.Before starting a simulation, several simulation parameters need to be set. These parameters are accessed by selecting Parameters from the Simulation menu in the model window (Ctrl+E). This displays a dialogue box in which the integration algorithm and other parameters for the simulation can be set.a)Check that the integration algorithm highlighted at the top of thedialogue box is ‘Runge-Kutta ODE4’.b)Start Time: The time at which the simulation is to start. Use thedefault. (default = 0.0)c)Stop Time: The time at which the simulation is to stop. The defaultfor this option usually needs to be changed. Enter ‘1’. (default =10)d)Initial Step Size: The initial time step that is used to solve themodel equations by integration. The ‘auto’ default is usuallysatisfactory.e)Max Step Size: The maximum time step that is used to solve themodel equations by integration. Too large a value and the accuracyof the simulation will be poor, the simulation can even becomeunstable. A suitable value depends on the dynamics of a particularsystem simulation. Set to 0.00001f)Select ‘OK’Run the simulation by selecting Start from the Simulation menu or the Toolbar.Plotting the resultsAfter successfully simulating the system, the variables t, sig1 and sig2 should be available in the MATLAB workspace. To see a list of the available variables type whosTo examine the data (not recommended for large simulations) type[t sig1 sig2]This produces a list of data with t=column1, sig1=column2 and sig2=column3.To plot the results of the simulation typeplot(t,sig1,t,sig2)This produces a plot of both sig1 and sig2 against t on the same graph. To plot only one of the variables, e.g. the output, typeplot(t,sig1)Using MATLAB to analyse the resultsAs you can see it’s possible to create simulations in SIMULINK and view the results using the Scope block, however the Scope block has two drawbacks. First of all itslows down the simulation considerably (if viewing the scope as the simulation is running) secondly its not possible to save the scope to the clipboard, the only way to do so is to use the Print Scrn button on your PC. Saving data to the MATLAB workspace allows you to use the built in MATLAB functions to analyses and post process the data. It also allows you to use the considerable MATLAB plotting options. It’s possible to enter the plot commands etc at the MATLAB command prompt, however in situations requiring multiple simulation runs it’s easier to use a m-file to perform the post processing. Below is an m-file that calculates and plots the FFT of sig2. Once you have created the m-file save it to your working directory for future use. Note that the variables should be named as in the SIMULINK model.Once the simulation has finished run the above m-file by either right clicking on the m-file in the MATLAB current directory window or pressing f5 with the m-file open. The resulting plots are given below.0.90.910.920.930.940.950.960.970.980.991-1-0.50.51Complex waveformTime (s)V o l t a g e (V )02468101214161820050100FFT of complex waveform Harmonic numberH a r m o n i c m a g n i t u d e , %0.90.910.920.930.940.950.960.970.980.991-1-0.8-0.6-0.4-0.20.20.40.60.81Component waveforms Time (s)V o l t a g e (V )。
Lab 1: Introduction to MATLAB1. Warm-upMATLAB is a high-level programming language that has been used extensively to solve complex engineering problems. The language itself bears some similarities with ANSI C and FORTRAN.MATLAB works with three types of windows on your computer screen. These are the Command window, the Figure window and the Editor window. The Figure window only pops up whenever you plot something. The Editor window is used for writing and editing MATLAB programs (called M-files) and can be invoked in Windows from the pull-down menu after selecting File | New | M-file. In UNIX, the Editor window pops up when you type in the command window: edit filename(…fi lename‟ is the name of the file you want to create).The command window is the main window in which you communicate with the MATLAB interpreter. The MATLAB interpreter displays a command >> indicating that it is ready to accept commands from you.● View the MATLAB introduction by typing>> introat the MATLAB prompt. This short introduction will demonstrate somebasic MATLAB commands.●Explore MATLAB‟s help capability by trying the following:>> help>> help plot>> help ops>> help arith● Type demo and explore some of the demos of MATLAB commands.● You can use the command window as a calculator, or you can use it tocall other MATLAB programs (M-files).Say you want to evaluate the expression a3 +√bd −4c , where a=1.2,b=2.3, c=4.5 and d=4. Then in the command window, type:>> a = 1.2;>> b=2.3;>> c=4.5;>> d=4;>> a^3+sqrt(b*d)-4*cans =-13.2388Note the semicolon after each variable assignment. If you omit the semicolon, then MATLAB echoes back on the screen the variable value.2. Arithmetic OperationsThere are four different arithmetic operators: + addition− subtraction * multiplication/ division (for matrices it also means inversion)There are also three other operators that operate on an element by element basis:.* multiplication of two vectors, element by element ./ division of two vectors, element-wise.^ raise all the elements of a vector to a power.Suppose that we have the vectors x = [1x ,2x , ..., n x ] and y = [1y ,2y , ...,n y ]. Thenx. * y = [11x y ,22x y , ..., n n x y ] x./y = [11x y ,22x y , ...,n nx y ]x.ˆp = [1p x ,2p x , ...,p n x ]The arithmetic operators + and - can be used to add or subtract matrices, scalars or vectors. By vectors we mean one-dimensional arrays and bymatrices we mean multi-dimensional arrays. This terminology of vectors and matrices comes from Linear Algebra.Example:>> X=[1,3,4] >> Y=[4,5,6] >> X+Y ans=5 8 10For the vectors X and Y the operator + adds the elements of the vectors, one by one, assuming that the two vectors have the same dimension. In the above example, both vectors had the dimension 1 × 3, i.e., one row with three columns. An error will occur if you try to add a 1 × 3 vector to a 3 × 1 vector. The same applies for matrices.To compute the dot product of two vectors (i.e. iP i i x y ), you can use themultiplication operator * . For the above example, it is:>> X*Y’ans =43Note the single quote after Y. The single quote denotes the transpose of a matrix or a vector.To compute an element by element multiplication of two vectors (or two arrays), you can use the .* operator:>> X .* Yans =4 15 24That is, X.*Y means [1×4, 3×5, 4×6] = [4 15 24]. The ….*‟ operator is used very often (and is highly recommended) because it is executed much faster compared to the code that uses for loops.3. Complex numbersMATLAB also supports complex numbers. The imaginary number is denoted with the symbol i or j, assuming that you did not use these symbols anywhere in your program (that is very important!). Try the following: >> z=3 + 4i % note that you do not need the …*‟ after 4>> conj(z) % computes the conjugate of z>> angle(z) % computes the phase of z>> real(z) % computes the real part of z>> imag(z) % computes the imaginary part of z>> abs(z) % computes the magnitude of zYou can also define the imaginary number with any other variables you like. Try the following:>> img=sqrt(-1)>> z=3+4*img>> exp(pi*img)4. Array indexingIn MATLAB, all arrays (vectors) are indexed starting with 1, i.e., y(1) is the first element of the array y. Note that the arrays are indexed using parenthesis (.) and not square brackets [.] as in C/C++. To create an array having as elements the integers 1 through 6, just enter:>> x=[1,2,3,4,5,6]Alternatively, you can use the : notation,>> x=1:6The notation above creates a vector starting from 1 to 6, in steps of 1. If you want to create a vector from 1 to 6 in steps of say 2, then type: >> x=1:2:6Ans =1 3 5Try the following code:>> ii=2:4:17>> jj=20:-2:0>> ii=2:(1/10):4Extracting or inserting numbers in a vector can be done very easily. To concatenate an array, you can use the [ ] operator, as shown in the example below:>> x=[1:3 4 6 100:110]To access a subset of the array, try the following:>> x(3:7)>> length(x) % gives the size of the array or vector>> x(2:2:length(x))5. Allocating memoryYou can allocate memory for one-dimensional arrays (vectors) using the zeros command.The following command allocates memory for a 100-dimensional array:>> Y=zeros(100,1);>> Y(30)ans =Similarly, you can allocate memory for two-dimensional arrays (matrices). The command>> Y=zeros(4,5)defines a 4 by 5 matrix. Similar to the zeros command, you can use the command ones to define a vector containing all ones,>> Y=ones(1,5)ans=1 1 1 1 16. Special characters and functionsSome common special characters used in MATLAB are given below:Some special functions are given below:length(x) - gives the dimension of the array xfind - Finds indices of nonzero elements.Examples:>> x=1:10;>> length(x)ans =10The function find returns the indices of the vector X that are non-zero. For example, I = find(X>100), finds all the indices of X when X is greater than 100. So for the aboveExample:>> find(x> 4)ans =5 6 7 8 9 107. Control flowMATLAB has the following flow control constructs:●if statements●switch statements●for loops●while loops●break statementsThe if, for, switch and while statements need to terminate with an end statement.Examples:IF:x=-3;if x>0str=’positive’;elseif x<0str=’negative’;elseif x= = 0str=’zero’;elsestr=’error’;endWhat is the value of ‟str‟ after execution of the above c ode? WHILE:x=-10;while x<0x=x+1;endWhat is the value of x after execution of the above loop?FOR loop:X=0;for i=1:10X=X+1;endThe above code computes the sum of all numbers from 1 to 10. BREAK:The break statement lets you exit early from a for or a while loop: x=-10;while x<0x=x+2;if x = = -2break;endendMATLAB supports the following relational and logical operators: Relational OperatorsSymbol Meaning<= Less than equal< Less than>= Greater than equal> Greater than== Equal˜ =Not equalLogical OperatorsSymbol Meaning& AND| OR˜ NOT8. PlottingYou can plot arrays using MATLAB‟s function plot. The function plot (.) is used to generate line plots. The function stem(.) is used to generate“picket-fence” type of plots.Example:>> x=1:20;>> plot(x) %see Figure 1>> stem(x) % see Figure 2Example of a plot generated using the plot command is shown in Figure 1, and example of a plot generated using the stem function is shown in Figure 2. More generally, plot(X,Y) plots vector Y versus vector X. Various line types, plot symbols and colors may be obtainedusing plot(X,Y,S) where S is a character string indicating the color of the line, and the type of line (e.g., dashed, solid, dotted, etc.). Examples for the string S include:You can insert x-labels, y-labels and title to the plots, using the functions xlabel(.), ylabel(.) and title(.) respectively. To plot two or more graphs on the same figure, use the command subplot. For instance, to show the above two plots in the same figure, type:>> subplot(2,1,1), plot(x)>> subplot(2,1,2), stem(x)The (m,n,p) argument in the subplot command indicates that the figure will be split in m rows and n columns. The …p‟ argument takes the values 1, 2. . . m×n. In the example above, m = 2, n = 1, and, p = 1 for the top figure and p = 2 for the bottom figure.To get more help on plotting, type: help plot or help subplot.9. Programming in MATLAB (M-files)MATLAB programming is done using M-files, i.e., files that have the extension .m. These files are created using a text editor. To open the text editor, go to the File pull-down menu, choose New, then M-file. After you type in the program, save it, and then call it from the command window to execute it.Say for instance that you want to write a program to compute the average (mean) of a vector x. The program should take as input the vector x and return the average of the vector.Steps:1. You need to create a new fi le, called “average.m”. If you are in Windows,open the text editor by going to the File pull-down menu, choose New,then M-file. If you are in UNIX, then type in the command window: editaverage.m. Type the following in the empty file________________________________function y=average(x)L=length(x);sum=0;for i=1:Lsum=sum+x(i);endy=sum/L; % the average of x________________________________Remarks:y —is the output of the function “average”x —is the input array to the function “average”average —is the name of the function. It‟s best if it has the same name as the filename. MATLAB files always need to have the extension .m2. From the Editor pull-down menu, go to File | Save, and enter:average.m for the filename.3. Go to the Command window to execute the program by typing:>> x=1:100;>> y=average(x)ans =50.5000Note that the function average takes as input the array x and returns one number, the average of the array. In general, you can pass more than one input argument and can have the function return multiple values. You can declare the function average, for instance, to return 3 variables while taking 4 variables as input with the following statement:function [y1, y2, y3]=average(x1,x2,x3,x4)In the command window it has to be invoked as:>> [y1, y2, y3]=average(x1,x2,x3,x4)10. MATLAB soundIf your PC has a sound card, then you can use the function soundsc to play back speech or audio fi les through the PC‟s speakers. The usage of this function is given below:soundsc(Y,FS) sends the signal in vector Y (with sample frequency FS) out to the speaker on platforms that support sound. Stereo sounds are played, on platforms that support it, when Y is an N-by-2 matrix.Try the following code, and listen to a 400-Hz tone:>> t=0:1/8192:1;>> x=cos(2*pi*400*t);>> soundsc(x,8192);Now, try listening to noise:>> noise=randn(8192,1); % generate 8192 samples of noise>> soundsc(noise,8192);The function randn generates Gaussian noise.11. Loading and saving dataYou can load or save data using the commands load and save. To save the variable x of the above code in the file data.mat, type:>> save data.mat xNote that MATLAB‟s data files have the extension .mat. To retrieve the data that was saved in the vector x, type:>> load data.matThe vector x is loaded in memory. To see the contents of memory use the command whos:>> whosName Size Bytes ClassX 1x8193 65544 double arrayGrand total is 8193 elements using 65544 bytesThe command whos gives a list of all the variables currently in memory, along with their dimension. In our case, x contained 8193 samples.To clear up memory after loading a file, you may type clear all when done. That is very important, because if you do not clear all the variables in memory, you may run into problems with other programs that you will write that use the same variables.。