You are on page 1of 6

MATLAB for Beginners EECE 660 (Dr. Bala Natarajan) Getting Started 1. What is MATLAB? MATrix LABoratory.

. Every data object is assumed to be an array/matrix. 2. Running MATLAB On a system running WINDOWS 2000, double click on the MATLAB icon and a command window will appear with the prompt: >> You are now in MATLAB and can use any command at the prompt. After you enter the command with the proper syntax and press <enter>, the processing will take place. 3. Programs and Functions Command Session Function .m file Script .m file normal C program) : run command after command : takes in variables and spits out variables : program (set of commands and functions like your

4. Getting help Help on the MATLAB main window provides a list of all commands and functions. You can type >> help it lists all the commands. If you know the command but are not sure how it works, just type >> help <command name> www.mathworks .com has a lot of useful help from beginners Other tutorials in other universities might be useful for getting an in-depth knowledge http://www.math.utah.edu/lab/ms/matlab/matlab.html http://www.math.ufl.edu/help/matlab-tutorial/matlab-tutorial.html#SEC1 And a lot more, just go to a search engine and type MATLAB Tutorial or MATLAB for Beginners Entering Variables The following commands show how to enter numbers, vectors and matrices, and assign them to variables. (Entering numbers) >> a = 2
a = 2

(Entering vectors/arrays)
>> x = [1;2;3] x = 1 2 3 (Entering matrices) >> A = [1 2 3;4 5 6;7 8 0] A = 1 2 3 4 5 6 7 8 0

Notice that the rows of a matrix are separated by semicolons, while the entries on a row are separated by spaces (or commas). A useful command is ``whos'', which displays the names of all defined variables and their types:
>> whos Name A a x Size 3x3 1x1 3x1 Bytes 72 8 24 Class double array double array double array

Grand total is 13 elements using 104 bytes

Note that each of these three variables is an array; the ``shape'' of the array determines its exact type. The scalar/number a is a 1x1 array, the vector x is a 3x1array, and A is a 3x3 array (see the ``size'' entry for each variable). Matlab allows arrays to have complex entries. The complex unit i=-1is represented by either of the built-in variables i or j:
>> sqrt(-1) ans = 0 + 1.0000i

This example shows how complex numbers are displayed in Matlab; it also shows that the square root function is a built-in feature. The arithmetic operators work as expected for scalars. A built-in variable that is often useful is :
>> pi ans = 3.1416

Other functions, such as sine, cosine, tangent, exponential, and logarithm are also predefined. For example:

>> cos(.5)^2+sin(.5)^2 ans = 1 >> exp(1) ans = 2.7183 >> log(ans) ans = 1

It is often useful, to suppress the display; this is done by ending the line with a semicolon. For example: >> pi; >> Other Useful Commands Some Basic Commands (Note command syntax is case-sensitive!) quit quits matlab, returning you to the operating system. exit same as quit. who lists all of the variables in your matlab workspace. whos list the variables and describes their matrix size. clear deletes all matrices from active workspace. clear x deletes the matrix x from active workspace. save <filename> saves the contents of workspace into filename.mat save <filename> x y z saves the matrices x, y and z into the file titled filename.mat. load <filename> loads the contents of filename into current workspace; the file can be a binary (.mat) file or an ASCII file. Commands Useful in Plotting creates an Cartesian plot of the vectors x & y. creates a plot of y vs. the numerical values of the elements in the yvector. semilogx(x,y) plots log(x) vs y. semilogy(x,y) plots x vs log(y) grid creates a grid on the graphics plot. title('text') places a title at top of graphics plot. xlabel('text') writes 'text' beneath the x-axis of a plot. ylabel('text') writes 'text' beside the y-axis of a plot. text(x,y,'text') writes 'text' at the location (x,y) . gtext('text') writes text according to placement of mouse hold on maintains the current plot in the graphics window while executing subsequent plotting commands. hold off turns OFF the 'hold on' option. polar(theta,r) creates a polar plot of the vectors r & theta where theta is in radians. bar(x) creates a bar graph of the vector x. plot(x,y) plot(y)

hist(x)

creates a histogram. This differs from the bargraph in that frequency is plotted on the vertical axis.

Data Analysis Commands max(x) min (x) mean(x) median(x) sum(x) prod(x) std(x) sort(x) length(x) size(x) rand randn rand(A) returns the maximum value of the elements of vector returns the minimum of x (see max(x) for details). returns the mean value of the elements of a vector returns the median value. returns the sum of the elements of a vector returns the product of elements. returns the standard deviation of the elements of a sorts the values in the vector x or the columns of a matrix and places them in ascending order. returns the number elements in a vector. returns the size m(rows) and n(columns) of matrix x. returns a (uniform distributed) random number between 0 and 1. returns a random number selected from a normal distribution with a mean of 0 and variance of 1. returns a matrix of size A of (uniform distributed) random numbers. addition subtraction multiplication right division (a/b means a b) left division (a\b means b a) exponentiation

Scalar Calculations. + * / \ ^

More System Commands cd text: CTRL-C delete file dir ls mkdir text pause pwd type file what Change current working directory to text. Causes an abort of a MATLAB command. Delete file file. Directory listing (see ls). List files and directories (see dir). Make directory text. Temporarily halts a MATLAB program. Print Working Directory. Displays the contents of the m-file file. Lists the m-files stored in the current directory

I would advise you to check the help for complete details on using all of these commands. This list is to get you started, so that you can explore in detail the vast variety of functions that are available in MATLAB.

Programming Tools The students should go and experiment with other typical programming constructs such as for loops, if else etc. The syntax in matlab is different from that in C and therefore it would be wise for you to check it when you start programming in matlab. These programming tools will be vital in helping you write programs in this course as well as in your future jobs! Few examples 1. Example of a function Assume you want to store the first N positive integers in an array/vector. The input variable to the function that you are going to create is N. The output of the function is vector A that has the N integers as its elements. Enter the MATLAB editor and create this file function [A] = posint(N) %POSINT positive integers for i=1:N, A(i) = i; end Store this file as posint.m and on the main command window type >> posint(5) >> ans = 1 2 3 4 5 This is how you access functions. 2. Example of another function function plotSINC(T) % plot complex frequency response of audio amplifier % H(f)=T*sin(pi*f*T)/(pi*f*T) for roughly % 5 bandwidths worth of frequency f_limit=5/T; f_step=.1/T; f=[-f_limit:f_step:f_limit]; % create frequency vector in units of hertz H_f=T*sinc(f*T); % sinc is built-in to MATLAB figure(1) % plot results title('Complex Frequency Response of an Audio Amplifier') axis([-f_limit f_limit -.3*T T]) plot(f,H_f) plot([-f_limit f_limit],[0 0],'k') xlabel('\it{f}');

ylabel('{\it{H}} ( {\it{f}} )'); When you type >> plotSINC(2) in the command window you get a sinc waveform. Try changing T value and see how the zero crossing of the waveform changes. 3. Example of a Script .m file Program %This is a symbol that you can use to comment your matlab code %This program plots a sine wave up to 10 periods clear ; %Clears all the old variables clc ; %clears the display screen f = 10; % Define the frequency of the sine wave as 10 Hz T = 1/f ;% Period of this sine wave is the inverse of the frequency time = [0: 0.01*T: 10*T]; % Defining an array or a vector of time instants from 0 to 10*T %spaced by 0.01*T apart at which we will determine the sine values (so that we can obtain a %smooth plot) x = sin(2*pi*f*time); % define a vector x and store the sine wave values in it figure(1); plot(time,x); xlabel(Time); ylabel(Amplitude); title( 10 periods of a sine wave); Now store this under any name you want say testsine.m. Go to the matlab command window and type >> testsine and observe the sine wave plot. You can use the input command to take variables into a Program (just like in a function). For example, the first function example can be written as a program like this: %Program to print out the 1st N positive integers clear ; clc ; N = input(Enter the number of integers you want :); for i=1:N, A(i) = i; end A When you save this as testint.m and execute it from the command window, it will prompt you for the value for N. Once you enter a value say 5, then it will execute the remaining program and output the vector A.

You might also like