<< Chapter < Page Chapter >> Page >
Introduction to MATLAB and script files. This development of these labs was supported by the National Science Foundation under Grant No. DUE-0511635. Any opinions, conclusions orrecommendations expressed in this material are those of the authors and do not necessarily reflect the views of the National Science Foundation.


The goal of this lab is to provide exercises that will help you get started learning MATLAB. You will learn about the help function, vectors, complex numbers, simple math operations, and 2-D plots. You may find it useful to try some of the built-in demos in Matlab. Type demo to see the choices. In particular, look at the demo on "Basic matrix operations" (under "Mathematics") and on "2-D" plots (under "Graphics"). We will also look at script files in MATLAB, which we will refer to as M-files and have the file extension *.m .

Getting started

Start MATLAB by clicking on it in the start menu. Once MATLAB is running you will see a screen similar to Figure 1. The command window, (A), is where you can enter commands. The current working directory, (B), displays the directory that MATLAB will look first for any commands. For example, if you made a new MATLAB function called myfunc.m , then this will need to be placed in the current working directory. You can change the working directory by typing it in the box, clicking the "..." button to browse to a folder, or typing cd [directory name] (i.e. cd 'H:\ee235\lab0\' ), which is similar to the DOS/Linux cd command).

MATLAB supports tab completion. This means that you can type part of a command and then press tab and it will fill in the rest of the command automatically.
The workspace displays information about all the variables currently active and is shown in (C). The files in the current directory can also be displayed in (C) by clicking on the tab labeled Current Directory . A history of your commands is shown in (D). If you find that you do not need some of these windows open you can close them by clicking on the small x in that section of the window.

The matlab gui

(a) Command window, (b) working directory, (c) workspace, (d) command history.

There are a number of different ways to use MATLAB on Linux. Typing matlab at the command prompt will run MATLAB in X-Windows (warning, MATLAB in X-Windows can be slow when connecting off campus). To run MATLAB without X-Windows type matlab -nodisplay . You can also run MATLAB using the current terminal for commands and use X-Windows for everything else (like figures) by typing matlab -nodesktop .

Matlab commands

MATLAB works with matrices and therefore treats all variables as a matrix. To enter the matrix x = ( 3 1 5 6 4 1 ) MathType@MTEF@5@5@+=feaafiart1ev1aaatCvAUfeBSjuyZL2yd9gzLbvyNv2CaerbuLwBLnhiov2DGi1BTfMBaeXatLxBI9gBaerbd9wDYLwzYbItLDharqqtubsr4rNCHbGeaGqiVCI8FfYJH8YrFfeuY=Hhbbf9v8qqaqFr0xc9pk0xbba9q8WqFfeaY=biLkVcLq=JHqpepeea0=as0Fb9pgeaYRXxe9vr0=vr0=vqpWqaaeaabiGaciaacaqabeaadaqaaqaaaOqaaiaadIhacqGH9aqpdaqadaqaauaabeqacmaaaeaacaaIZaaabaGaaGymaaqaaiaaiwdaaeaacaaI2aaabaGaaGinaaqaaiaaigdaaaaacaGLOaGaayzkaaaaaa@3DF1@ type the command x = [3 1 5; 6 4 1] . We can represent an array with a vector, which is a special case of a matrix. A vector can be entered in by typing y = [1 2 3] . Now try entering z = [1 2 3]' . Is the output what you expect?

  • Familiarize yourself with the help command. Typing help gives you a list of all help topics. Typing help<topicname> gives help on a specific MATLAB function. For example, use help plot to learn about the plot command.

    More useful commands

    • whos lists all variables
    • clear clears all variables
  • Perform the following operations in MATLAB:
    • Generate the following column vectors as MATLAB variables: x = ( 2 4 ) MathType@MTEF@5@5@+=feaafiart1ev1aaatCvAUfeBSjuyZL2yd9gzLbvyNv2CaerbuLwBLnhiov2DGi1BTfMBaeXatLxBI9gBaerbd9wDYLwzYbItLDharqqtubsr4rNCHbGeaGqiVCI8FfYJH8YrFfeuY=Hhbbf9v8qqaqFr0xc9pk0xbba9q8WqFfeaY=biLkVcLq=JHqpepeea0=as0Fb9pgeaYRXxe9vr0=vr0=vqpWqaaeaabiGaciaacaqabeaadaqaaqaaaOqaaiaadIhacqGH9aqpdaqadaqaauaabeqaceaaaeaacaaIYaaabaGaaGinaaaaaiaawIcacaGLPaaaaaa@3AF5@ and y = ( 3 1 ) MathType@MTEF@5@5@+=feaafiart1ev1aaatCvAUfeBSjuyZL2yd9gzLbvyNv2CaerbuLwBLnhiov2DGi1BTfMBaeXatLxBI9gBaerbd9wDYLwzYbItLDharqqtubsr4rNCHbGeaGqiVCI8FfYJH8YrFfeuY=Hhbbf9v8qqaqFr0xc9pk0xbba9q8WqFfeaY=biLkVcLq=JHqpepeea0=as0Fb9pgeaYRXxe9vr0=vr0=vqpWqaaeaabiGaciaacaqabeaadaqaaqaaaOqaaiaadMhacqGH9aqpdaqadaqaauaabeqaceaaaeaacaaIZaaabaGaaGymaaaaaiaawIcacaGLPaaaaaa@3AF4@
    • Using the computer, issue the following MATLAB commands x * y' x' * yx .* y Be sure you understand the differences between each of these and you know what the ' , * , and .* operators do.
    • Convince yourself that the answer makes sense by checking the matrix dimension and computing each result by hand.
  • Plot and subplot

    The Matlab command plot allows you to graphically display vector data (in our case here, the two signals). For example, if you had the variables t for time, and y for the signal, typing the command plot(t, y); will display a plot of t vs. y . See help plot for more information.

    Annotating your plots is very IMPORTANT! Here are a few annotation commands.

    • title('Here is a title'); - Adds the text "Here is a title" to the top of the plot.
    • xlabel('Control Voltage (mV)'); - Adds text to the X-axis.
    • ylabel('Current (mA)'); - Adds text to the Y-axis.
    • grid on; - Adds a grid to the plot.

    In order to display multiple plots in one window you must use the subplot command. This command takes three arguments, subplot(m, n, p) . The first two breaks the window into a m by n matrix of smaller plot windows. The third argument, p, selects which plot is active.

    For example, if we have three signals x, y, and z, that we want to plot against time, t, then we can use the subplot command to produce a single window with three plots stacked on top of each other. subplot(3,1,1); plot(t,x);subplot(3,1,2); plot(t,y);subplot(3,1,3); plot(t,z);

    See help subplot and help plot for much more information.

    Create and plot a signal x 0 ( t ) = t e | t | MathType@MTEF@5@5@+=feaafiart1ev1aaatCvAUfeBSjuyZL2yd9gzLbvyNv2CaerbuLwBLnhiov2DGi1BTfMBaeXatLxBI9gBaerbd9wDYLwzYbItLDharqqtubsr4rNCHbGeaGqiVCI8FfYJH8YrFfeuY=Hhbbf9v8qqaqFr0xc9pk0xbba9q8WqFfeaY=biLkVcLq=JHqpepeea0=as0Fb9pgeaYRXxe9vr0=vr0=vqpWqaaeaabiGaciaacaqabeaadaqaaqaaaOqaaiaadIhadaWgaaWcbaGaaGimaaqabaGccaGGOaGaamiDaiaacMcacqGH9aqpcaWG0bGaamyzamaaCaaaleqabaGaeyOeI0IaaGymamaaemaabaGaamiDaaGaay5bSlaawIa7aaaaaaa@42FA@ over the time range [-10,10] using the following MATLAB commands: t = -10:0.1:10; xo = t .* exp(-abs(t));plot(t, xo); grid; The first command defines an array with time values having an 0.1 increment. The ";" is used to suppress printout of the arrays (which are large), and the "grid" command makes the plot easier to read. Now create the signals:
    x e t t e t
    x ( t ) = 0.5 * [ x 0 ( t ) + x e ( t ) ] MathType@MTEF@5@5@+=feaafiart1ev1aaatCvAUfeBSjuyZL2yd9gzLbvyNv2CaerbuLwBLnhiov2DGi1BTfMBaeXatLxBI9gBaerbd9wDYLwzYbItLDharqqtubsr4rNCHbGeaGqiVCI8FfYJH8YrFfeuY=Hhbbf9v8qqaqFr0xc9pk0xbba9q8WqFfeaY=biLkVcLq=JHqpepeea0=as0Fb9pgeaYRXxe9vr0=vr0=vqpWqaaeaabiGaciaacaqabeaadaqaaqaaaOqaaiaadIhacaGGOaGaamiDaiaacMcacqGH9aqpcaaIWaGaaiOlaiaaiwdacaGGQaWaamWaaeaacaWG4bWaaSbaaSqaaiaaicdaaeqaaOGaaiikaiaadshacaGGPaGaey4kaSIaamiEamaaBaaaleaacaWGLbaabeaakiaacIcacaWG0bGaaiykaaGaay5waiaaw2faaaaa@4892@
    Plot all signals together using 3 plots stacked on top of each other with the subplotcommand. subplot(3,1,1); plot(t,xo);subplot(3,1,2); plot(t,xe);subplot(3,1,3); plot(t,x); Note that x o ( t ) and x e ( t ) are the odd and even components, respectively, of x t t e t u t
  • Complex Numbers: One of the strengths of MATLAB is that most of its commands work with complex numbers. Perform the following computations in MATLAB.
    • MATLAB recognizes i as an imaginary number. Try entering sqrt(-1) into MATLAB, does the result make sense?
    • MATLAB uses the letter i instead of j by default. Electrical Engineers prefer using j however, and MATLAB will recognize that as well. Try entering i+j , does this make sense.
      If you are using complex numbers in your code, it's a good idea to avoid using i and j as variables to prevent confusion.
    • Define z 1 = 1 + j . Find the magnitude, phase, real and imaginary parts of z (using abs() , angle() , real() , imag() , respectively). Is the phase in radians or degrees?
    • Find the magnitude of z 1 + z 2 where z 2 2 e 3
    • Compute the value of j j MathType@MTEF@5@5@+=feaafiart1ev1aaatCvAUfeBSjuyZL2yd9gzLbvyNv2CaerbuLwBLnhiov2DGi1BTfMBaeXatLxBI9gBaerbd9wDYLwzYbItLDharqqtubsr4rNCHbGeaGqiVCI8FfYJH8YrFfeuY=Hhbbf9v8qqaqFr0xc9pk0xbba9q8WqFfeaY=biLkVcLq=JHqpepeea0=as0Fb9pgeaYRXxe9vr0=vr0=vqpWqaaeaabiGaciaacaqabeaadaqaaqaaaOqaaiaadQgadaahaaWcbeqaaiaadQgaaaaaaa@37ED@ . Is the result what you expect?
  • Complex Functions: MATLAB also handles complex time functions in the same way (again, implemented as vectors) . Create a signal x 1 t t e jt over the range [-10,10], as in part 3. Next plot the real and imaginary parts of the signal in two plots, one over the other using the subplot command. Notice that oneplot is odd and one is even. Try proving to your self analytically that this is what you would expect.
  • Playing and Plotting a Sound Load the built-in data named "handel" and play it: load handel; plot(linspace(0,9,73113),y);sound(y);
You can use the clear command in MATLAB to clear all of the varibles

Script files

Scripts are m-files files that contain a sequence of commands that are executed exactly as if they were manually typed into the MATLAB console. Script files are useful for writing things in MATLAB that you want to save and run later. You can enter all the commands into a script file that you can run at a later time, and have the ability to go back and edit it later.

You need to use a text editor to create script files, e.g. Notepad on the PC's ( pico , emacs , or vi on Linux machines). MATLAB also has an internal editor that you can start by clicking on a .m file within MATLAB's file browser. All are easy to learn and will produce text files that MATLAB can read.

Click here to download the dampedCosine.m script and be sure to save it with that name to follow the instructions here exactly. It is very important that script filenames end in .m . Be sure that MATLAB's working directory is set to the location of where you saved the script file. Type dampedCosine at the MATLAB prompt. Look at the m-file in a text editor and verify that you get the plot predicted in the comment field of the script.

The % character marks the rest of the line as a comment.


Now we are going to edit the dampedCosine.m file to create our own script file. At the top of the file, you will see the following commands

diary 'your_name_Lab1.txt' disp('NAME: your name')disp('SECTION:your section')

  • Edit the dampedCosine.m (download from link above) script and enter your name and section where indicated. Save this new version of the script as yourName_dampedCosine.m
  • Edit the script to create a second signal where the cosine with twice the period (which gives half the frequency) of the first.
  • Add to the script the commands to plot these together with the first signal on top and the second on the bottom. In other words, you should have a single figure with two different plots, one on top and one on bottom. You will need to use subplot and plot . Save this plot as yourName_dampedCosine.fig .
  • Show the TA your dampedCosine plot. What is the period of the cosine?

Complex exponentials

Download and run compexp.m , which includes a 3-D plot of a complex exponential, y t , as well as 2-D magnitude/phase and real/imaginary plots. You need 2 2-D plots to have the same information as the 3-D plot. How would you change the script to make the oscillation frequency lower by half? How would you change the script to make the decay faster? Show the TA your plots.

Questions & Answers

important of enocomic
Adu Reply
what is division of labour
Dennis Reply
division of labour can be defined as the separation of task to individuals in any economic system to specialize on it.
what is demand curve
Victoria Reply
demand curve is a downward sloping economic graph that shows the relationship between the price of product and the quantity of the product demanded.
What is demand
Frank Reply
It refers to the quantity of a commodity purchased in the market at a price and at a point of time.
refers to amount of commodities a consumer is willing and able to buy at particular price within a period of time
It is the ability and willingness a customer buys a product or service at a particular price, place and time while other things remaining constant or the same
In which case is opportunity cost is zero
Francis Reply
where no alternative is available
who is the father of economic
Omar Reply
Adam Smith
Adam Smith
Adam smith
Adam Smith
What is monopoly
Mauthoor Reply
it an economic situation where one individual controls the essential commodities or value product for maximum profit
monopoly is a market situation in which there is only one producer of a good or service which has no close substitutes
is where only one person is solely the price taker
what is Monopoly
Dauda Reply
The word Monopoly is a Latin word. it is the combination of two words-Mono means single and Poly means seller. thus Monopoly means single seller. but this is not the full meaning of Monopoly. Monopoly must produce a product which does not have close substitute in the market.
Monopoly is define as a firm in an industry with very high barriers to entry.
If close substitute is available, Monopoly will be a king without a crown.
what does it array
Cbdishakur Reply
what are the differences between monopoly and.oligopoly
Onome Reply
what are the difference between monopoly and oligopoly
The deference between Monopoly and Oligopoly: Monopoly means:A single-firm-Industry producing and selling a product having no close business and Oligopoly means:A market structure where a few sellers compete with each other and each controls a significant portion of market .
so that the price-output policy one affects the other.
what are difference between physical policy and monotory policy
what is economic
Emakpor Reply
what is economic
the word economic was derived from the Greek word oikos (a house)and mein(to manage) which in effect meant managing a household with the limited funds available 🙂.
good excample about scarsity
An Enquiry into the nature and causes of wealth Nations, this book clearly defined what economic is🙂🙂🙏🙏 thank you...
good example about scarcity: money,time, energy, human or natural resources. Scarcity of resources implies that there supply is very much limited in relation to demand.
equilibrium is a situation in which economic forces such as demand and supply are balanced and in the absence of external influences,the value of economic variables will not change
Onome Reply
marginal cost and marginal revenue is equilibrium .
what is equilibrium
Rodrice Reply
policy prescriptions for unemployment
Jeslyne Reply
Am working on it
what are the factors effecting demand sedule
Kalimu Reply
we should talk about more important topics, you can search it on Google n u will find your answer we should try to focus on how we can improve our society using economics
so good night
Why do people buy more grapes in December than in July?
because at time know money
Researchers demonstrated that the hippocampus functions in memory processing by creating lesions in the hippocampi of rats, which resulted in ________.
Mapo Reply
The formulation of new memories is sometimes called ________, and the process of bringing up old memories is called ________.
Mapo Reply
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get the best Algebra and trigonometry course in your pocket!

Source:  OpenStax, Continuous time linear systems laboratory (ee 235). OpenStax CNX. Sep 28, 2007 Download for free at http://cnx.org/content/col10374/1.8
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Continuous time linear systems laboratory (ee 235)' conversation and receive update notifications?