# Matlab Tutorial for Beginners

Writer: Zixu Zhu || Email: sz_jamesrei@hotmail.com

The topics below are the most important topics selected from the result of students' survey. This tutorial is for those who have never touched matlab before or need some review for matlab.

MATLAB is a numerical computing environment and programming language. Created by The MathWorks, MATLAB allows easy matrix manipulation, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages. Many classes in our ECEn Department requires professional skill using matlab, such as ECEn 360, ECEn 370, ECEn 380, ECEn 483...

## Vectors, matrix and arrays

- Setting up a vector or array
- One dimension arrays and vectors are almost the same in Matlab. You can use either vector or array form to store variables.
- Vector Format: x=a : b
- Array Format (one dimensional): x= [a:b], a is the beginning value, b is the ending value, the default step is 1
- For example
- a=[1:3], or a=1:3
- a is stored as: 1 2 3

- If you want to change the step length, the format is: x=a:"length of step":b
- For example:
- a=-1:0.5:1
- a is: -1.0000 -0.5000 0 0.5000 1.0000

- Of course, you can also set each element by hand, using a space to separate each element in the row, and a semicolon to separate each row.
- For example:
- a=[1 3 7 11;3 6 4 1]
- a will be:
- 1 3 7 11
- 3 6 4 1

- Useful default arrays
- Matlab has 2 useful default arrays: zeros, and ones. Each is an array filled with either zeros or ones. The format is : zeros/ones("number of dimension", length of array);
- For example:
- a=zeros(1,3)
- a is stored as: 0 0 0
- a=ones(1,3)
- a is stored as: 1 1 1

- With these two useful arrays, you can save time on setting values. For example, if you want to simulate a step function: x=[zeros(1,5) ones(1,5)], then x will be: 0 0 0 0 0 1 1 1 1 1

- Operations between arrays
- After setting the variables, you can do normal operations between arrays. To make an operation work on an array, just add a dot before the normal operator.
- For example:
- a=1:4;
- b=a.^(1/2)
- the result will be: b = 0.5000 1.0000 1.5000 2.0000

- Or, you can also use b=sqrt(a), the result is same.
- You don't need to set a for loop like in other programming languages to calculate the value of each element in b. Matlab will do it itself.
- Another example:
- x=1:4;
- y=sin(x)+2.*x
- y will be: 2.8415 4.9093 6.1411 7.2432

## Graphing

1. After setting and operating on arrays, the best way to see the behavior of x and y, or x,y, and z is to graph them. The most common functions for graphing are; plot, stem, polar, subplot, mesh, meshc, surf, surfc , and hold on.

2. Plot and stem:

- The format for these is the same. They both are: plot/stem(x,y).
- The difference is: plot will plot a continuous graph; stem is for the discrete graph.
- For example:
- x=-pi:0.1:pi;
- y=sin(x);
- plot(x,y)
- The result is:

For stem(x,y) the result will be:

3. Polar graph:

- Occasionaly, polar graphs may be better to see the relation between 2 variables. In EcEn 360, to graph the signal of an antenna, using a polar function is useful.
- Similar to plot and stem commands, the format for a polar graph is: polar(x,y).
- p.s. In this case, x probably is always an angle with a range of 0 to 2pi.
- For example:
- x=0:0.01:2*pi;
- y=sin(2*x).*cos(2*x);
- polar(x,y)
- The output will be:

4. 3D graph:

- Some times we need to see the behavior of three variables. In EcEn 360, it's required to plot a 3D graph of the probability with two variables. There are many useful functions that can simulate 3D graphs depending on which one you need.
- plot3:
- This function is mainly used for parametric functions, the syntax is: plot3(X1,Y1,Z1,...) where X1, Y1, Z1 are vectors or matrices. It will plot one or more lines in three-dimensional space through the points whose coordinates are the elements of X1, Y1, and Z1.
- For example:
- t = 0:pi/50:10*pi;
- plot3(sin(t),cos(t),t)
- grid on
- axis square
- the result will be:

5. Mesh and Surf:

- The syntax for these two functions is very similar to plot3, both are: mesh/surf(x,y,z). The difference is that these two functions will output a surface graph instead of only the connections of the dots.
- For example:
- [X,Y] = meshgrid(-2:.2:2, -2:.2:2);
- Z = X .* exp(-X.^2 - Y.^2);
- surf(X,Y,Z)
- the output will be:

If mech is replaced by surf, then the result will be:

P.S. In this program, [X,Y] = meshgrid(x,y) transforms the domain specified by vectors x and y into arrays X and Y, which can be used to evaluate functions of two variables and three-dimensional mesh/surface plots. The rows of the output array X are copies of the vector x; columns of the output array Y are copies of the vector y.

6. Mesh and view:

- These two functions will give you the idea of a 3D graph in a 2D one. "meshc" function will give you the contour plot of a 3D graph. "view(2)" will give you the view of a 3D graph when looking down from the top of it.
- For example:
- We can just add the "meshc(X,Y,Z)" at the end of last example to compare the results:
- [X,Y] = meshgrid(-2:.2:2, -2:.2:2);
- Z = X .* exp(-X.^2 - Y.^2);
- mesh(X,Y,Z)
- meshc(X,Y,Z)
- the result will be:

i. Same for the view function:

ii. [X,Y] = meshgrid(-2:.2:2, -2:.2:2);

iii. Z = X .* exp(-X.^2 - Y.^2);

iv. surf(X,Y,Z)

v. view(2)

vi. The result will be:

## Derivative and Integration

- Matlab can simulate both Integration and Derivative, not formulaically but by numerical approximation.
- So, if you want a mathematical formula of a derivative, use a calculator or another program.
- Derivative
- Matlab is able to do differences and approximate derivatives, the basic function is diff.
- The Syntax is: Y = diff(X) or Y = diff(X,n), n is the dimension of the derivative (such as a second derivative, third derivative, etc.) If n=1, it is the same as y=diff(x).
- diff(x)
- y=diff(X) calculates differences between adjacent elements of X.
- If X is a vector, then diff(X) returns a vector, one element shorter than X, of differences between adjacent elements:y=[X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]
- If X is a matrix, then diff(X) returns a matrix of row differences: [X(2:m,:)-X(1:m-1,:)]
- For example:
- x = [1 2 3 4 5];
- y = diff(x)
- result is: y = 1 1 1 1

- Furthermore, if the step in x is small enough, we can approximate its derivative:
- For example:
- step=0.001;
- x=0:step:2*pi;
- y=sin(x);
- z=diff(sin(x))/step;
- subplot(1,2,1);
- plot(y);
- subplot(1,2,2);
- plot(z);
- In this case, z is the derivative of y=sin(x), it should be cos(x)
- So from the plot we can see it is:

d. diff(X,n)

- Y = diff(X,n) applies diff recursively n times, resulting in the nth difference. For example, diff(X,2) is the same as diff(diff(X)). So for the first example above, if you type: z = diff(x,2) The result will be "z = 0 0 0"

4. Integral

- Integrals work similar to derivatives. Matlab can also approximate implement integrals. There are many functions that can do this, such as: cumsum, trapz, quad, etc. The cumsum function is the most useful one.
- The syntax is: B = cumsum(A). It returns the cumulative sum along different dimensions of an array. If A is a vector, cumsum(A) returns a vector containing the cumulative sum of the elements of A. If A is a matrix, cumsum(A) returns a matrix the same size as A containing the cumulative sums for each column of A.
- For example:
- x=0:0.1:10;
- y=sin(x);
- z=cumsum(y)*0.1;
- plot(x,z)
- The result shows the integral of sin(x):

## Signal processing

- The number one important operation in simulating a system or signal is a convolution.
- Before we look at a convolution, let's first simulate two very useful functions: the delta function and step function.
- We can use long arrays storing zeros and ones to approximately simulate those two functions.
- For example:
- Impulse function:
- nx=-50:50;
- x=[zeros(1,50) 1 zeros(1,50)];
- plot(nx,x);
- The output will be:

- Impulse function:

2. Step function:

- nx=-50:50;
- x=[zeros(1,50) ones(1,51)];
- plot(nx,x);
- The plot of result will be:

5. Now, we can look at the convolution. The syntax is just like this: conv(f1,f2);

6. For example

- Let's convolt these two functions:
- X=cos(n^2)*sin(2*pi*n/5)*u(t) and h=((0.9)^n)*(u(t)-u(t-10))
- Then the code will be:
- n=0:99;
- unit=ones(1,100);
- unit_10=[ones(1,11) zeros(1,89)];
- h=((0.9).^n).*unit_10;
- x=cos(n.^2).*sin(2*pi*n/5).*unit;
- y=conv(x,h);
- subplot(2,2,1);
- stem(n,x);
- subplot(2,2,2);
- stem(n,h);
- subplot(2,2,3);
- stem(n,y(1:100));
- The result is:

Filter and sampling processing will be taught in detail in ECEn380 class.

## Help and look for function

The Help function is the most useful function in Matlab. It lists all primary help topics in the Command Window. Each main help topic corresponds to a directory name on the MATLAB search path.

The Syntax of help function is:

help /

This command lists all operators and special characters, along with their descriptions.

help functionname

This command displays M-file help, which is a brief description and the syntax for functionname, in the Command Window. The output includes a link to doc functionname, which displays the reference page in the Help browser, often providing additional information. I think that doc link is the most useful link in Matlab. It should contains all you want to know.

## A very convenient tool of MATLab 7.0 for graphing

- If you don't like coding and still want to see the behavior of a function or two functions, the easiest way to do that in MatLab 7.0 is using the "funtool" function.
- First, type "funtool" in the Command Window like this:

3. Then, 3 windows(Figures) will show up (click image to enlarge):

4. These three images are the basis of the "funtool" function (click images to enlarge):

5. Figure 1:

- It is the graph of function f which will be defined in Figure 3.

6. Figure 2:

- It is the graph of function g which will also be defined in Figure 3.

7. Figure 3:

8. Function input windows:

- "f=": type in the expression of f function with variable x, the default expression is "x"
- Example for f=x^2:

a."g=": same as f function, type in the expression of g function , the default expression is "1"

b. Example for g=sin(x):

9.Range of x window("x="):

- Input the range of x in "x=" window, the format is "[starting value, ending value]"
- For Example, if we want x from -3pi to 3pi:

10. "a=" window:

- This is window is to set the value of "a" which is a factor of f. It may shift, shrink or enlarge the function f. The default value is �.

11. operation panel

- As you see, you can do almost all the common operations between these two functions or just one function itself. The result plot will show up in Figure 2 or Figure 3.

If you have any other questions, you can find the answers in this detailed matlab tutorial