Matlab for Microelectronics

Spring, 2020

Matlab for Electrical Engineering

Matlab is a powerful software suite useful for nearly all aspects of an electrical/computer engineer’s professional work. It is one of the most widely used programming languages in the ECE field. It’s like a combination of a calculator, a programming language, and a data analysis tool.

In-App Documentation

Matlab opens in a Command Window and gives you a command prompt. At this prompt, you can access in-terminal documentation for any command by using the help command. For example, we can request help for the disp command:

help disp

To access Matlab’s full documentation window, you can use the doc command like this:

doc disp

The help command is useful for getting fast information whereas the doc command is more in-depth, often with examples and tutorials.

Matlab Scripts: [name].m

A Matlab program is called a script, which means it is a sequence of commands that you could type into the command window. The script is interpreted rather than compiled. Matlab interprets one line at a time while the script is being run. For simple calculations, it’s convenient to type straight into the command window. For more complex programs, or for programs that need to be repeatable, you should write a script.

Matlab scripts conventionally end with a .m file type. You can create and edit scripts directly within the command window by clicking New Script in the menu bar.

For ECE courses, you are encouraged to prepare your homework solutions in Matlab scripts. By using scripts, your reasoning is clearly documented and it becomes easier to correct errors and reuse methods.

Comments

Comments in Matlab begin with a %. It is helpful to add comments throughout script files to clarify what’s intended. A comment can be placed inline, like this:

x = 2; % Setting x to 2

In this tutorial, we will sometimes use inline comments like this, but you are not required to type the comments as you work through the example commands.

Functions

A Matlab script can be used to define a new command with the same name as the file. For example, look at the top of the window for the “New” button and click it. A text editor should open with a blank page. Type these lines:

% my_function.m
% By:   [Your Name]
% Date: [The Current Date]
%
% Description:
%   Inputs:  x (scalar)
%   Outputs: y (scalar)
%
% Computes y = 2x
%

function y = my_function(x)

y = 2*x;

end % my_function

Once you’ve typed the lines above, click “Save” and save it with the name my_function.m. Then, in the Matlab command window, run the function:

x = 2;
y = my_function(x)

When you define a function, the heading provides help text. This is crucial if you intend to share your function with others, or if you want to use the script again in the future (you might forget what it does).

help my_function

Private functions

You can define multiple functions within a script file, but only one function can be accessed by users (the function name must match the file name). Any other functions can be accessed only from within the script file.

Edit the my_function.m file and make these changes:

    function y = my_function(x)

    y = private_function(x);

    end % my_function
    
    
    function y = private_function(x)
    
    y = 2*x;
    
    end % private_function

Save the file, then in the command window you can run my_function(x) but not private_function(x).

x = 2;
my_function(x)

Functions with Multiple Outputs

A function can support multiple outputs using this syntax:

function [y, z] = my_function(x)

y = 2*x;
z = 3*x;

end % my_function

Modify my_function.m to return y=2x and z=3x. Then save it and run it at the prompt.

[y,z] = my_function(x)

Matlab Syntax

If you are new to Matlab, begin by entering all the example lines shown below, one at a time, into the command window. This is so you can build some experience with how Matlab works and what it can do for you.

Variables

By default, every variable in Matlab is a vector or matrix of double-precision floats. Variables are declared and defined in a single statement:

x = 2

The above statement creates a variable named x with a value of 2.00. We can use x as a scalar value, but Matlab also treats it as a vector of length 1.

To declare a vector with multiple elements, type a list of numbers inside square brackets:

x = [2 4 5 4 2]

We can also declare an empty vector:

x = []

And we can concatenate values to incrementally fill up the vector:

x = [x 2]
x = [x 4]
x = [x 5 4 2]

Matlab also has a useful sequence notation:

x = 1:10 
x = 0:2:10

In general, a sequence is declared by three numbers separated by colons as start:step:end. You can also concatenate a sequence with other vector entries:

x = [1:1:8 9 10]

A matrix is defined by using a semi-colon or carriage return to separate the rows:

x = [1 2 3; 4 5 6]
x = [7 8 9
    10 11 12]

Vector and matrix variables are indexed from 1, going from top-to-bottom and then left-to-right. Matrix elements can be selected using a single index value, or using Cartesian indices as (row,column):

x = [1 2 3; 4 5 6]
x(1)
x(2)
x(1,1)
x(1,3)

You can also use sequence indexing to extract sub-vectors and submatrix ranges:

x = [1 1 2 3 5 8 13 21]
x(1:3)
x(1:2:8)

Another example:

x = [1:4; 5:8; 9:12]
x(2,:)
x(:,2)
x(2:3,2:3)

It is also often useful to transpose a matrix using the symbol:

x = [1 2 3]'

Matrix Algebra

Matlab’s real strength lies in matrix operations. You can directly multiply two matrices if they have compatible dimensions:

x = [1 2 3
     4 5 6]
y = [1 2
     3 4
     5 6]
x*y
y*x

You can also multiply a vector into a matrix in the usual way:

x = [1 2 3
     4 5 6]
y = [1 2] 
y*x

And you can add vectors or matrices:

x = [1 2 3]
y = [4 5 6]
x+y

You can also build a matrix by the product of two vectors:

x = [1 2 3]
y = [1
     2
     3]
y*x

Looping and Conditionals

For Loops

A Matlab for-loop is initiated using the for keyword, and the loop scope is terminated by an end statement as in this example:

x = 1:100
for idx=1:5
   disp(x(idx))
end

While Loops

The while-loop below does the same thing as the for-loop example.

x   = 1:100
idx = 1;

while (idx < 6)
   disp(x(idx))
   idx = idx + 1;
end

If-Else

x = 2;
y = 0;

if (x > 1) 
   disp('true')
   y = 1;
else
   disp('not true')
end

Vectorized Operations and Functions

In addition to conventional looping and branching constructs, it is often much faster to use vector and matrix functions. A few important examples are listed here. As a rule, Matlab programs will run much faster if vectorized functions are used instead of loops.

Termwise operators .* and .^

You can multiply two vectors term-by-term:

x = [1 2 3 4]
y = [2 2 1 1]
x.*y

Similarly you can exponentiate all terms of a vector:

x = [1 2 3 4]
x.^2

You can also termwise-multiply two matrix variables:

x = [1 2 3; 1 2 3; 1 2 3]
y = [2 2 2; 2 2 2; 2 2 2]
x.*y

And you can termwise-multiply a vector with a matrix. In this instance, the vector is applied to all the rows in the matrix:

x = [1 1 1; 1 1 1; 1 1 1]
y = [1 2 3]
x.*y

find

The find command performs a search to find elements that satisfy a condition:

x = 2:2:10
find(x==4)

In the above example, find returns the index of the matching element, which appears at index 2. Suppose we search for something that doesn’t exist:

find(x==5)

In this case, the find command returns an empty array.

When there are multiple matches, the find command returns a vector containing all the matching indices.

find(x>5)

returns [3 4 5]. If only the first K matches are desired, find can be provided an additional argument:

find(x>5,2)

returns [3 4], and

find(x>5,1)

returns the scalar value 3.

One of the most common applications of the find command is to apply a command across all matching entries. For example:

x(find(x>5)) = 5

returns [2 4 5 5 5]. In human language, this statement says “find all elements of x that are greater than 5, and set them equal to 5.”

sum

The sum command adds together all elements in a vector, or all rows in a matrix. Examples:

x = [1 1 1 1 1 1]
sum(x)

This returns 6. Next, a matrix example:

x = [1 1 1; 1 1 1]
sum(x)

This returns [2 2 2]. Now, a transposed maxtrix example:

x = [1 1 1; 1 1 1]
sum(x')

This returns [3 3] since it sums across the columns of x.

cumsum

The “cumulative sum” function, abbreviated as cumsum, computes the incremental summation over a vector. The result is essentially a discrete integral. In the example below, we provide a square function, and use cumsum to “integrate” the square:

x = [1 1 1 1 -1 -1 -1 -1]
cumsum(x)

The result is [1     2     3     4     3     2     1     0], a triangle function, which is the expected piecewise-linear integral of a square step function.

diff

The diff function computes the pairwise difference between neighboring elements in a vector. This is similar to a discrete derivative:

x = [0 1 2 3 4 3 2 1 0]
diff(x)

This returns [1     1     1     1    -1    -1    -1    -1], making it the inverse of the cumsum function.

movsum

This command computes a sliding window sum of width K:

K=2
x = 1:10
movsum(x,K)

This returns [1   3   5   7   9  11  13  15  17  19], i.e. it returns 0+x(1), x(1)+x(2), x(2)+x(3), and so on.

max, min

These return the maximum and minimum values in a vector. They do not return the positions of max or min values.

x = 1:10
max(x)
min(x)

abs

The absolute value or complex magnitude of all elements in a vector.

x = -10:10
abs(x)

Input and Output

Matlab excels at plotting, but we will begin with simpler text I/O commands.

fprintf

The fprintf command can be used to write text to a file or to the command window. The command below writes “hello world” to the command window:

fprintf(1, "hello world\n")

In this example, the first argument is the number 1, which instructs Matlab to write output into the command window rather than to a file.

The Matlab fprintf function is based on the C fprintf function. It has the same capability for formatted output. This example writes a numerical value to the command window:

x=3
fprintf(1, "The value of x is %d\n", x)

Several of the C % codes are supported. Here are some of the more important ones:

code type
%d decimal integer
%x hexadecimal integer
%d octal integer
%f floating point number
%e scientific notation
%g compact scientific
%s string

You can also add parameters to control how numbers are displayed. For example, we can control how many digits are allowed on the left and right side of the decimal point:

x = 13.75
fprintf(1,"x = %12.4f\n", x)

In the example above, the “12” instructs the function to display the number in exactly 12 characters. The “.4” indicates that there should be four digits after the decimal point, and the “f” indicates a floating point number.

For printing text to a file, you first need to open the file using the fopen command. Then use fprintf to write text into the file, and finally close the file with fclose. Here is an example:

x = 13.75
file_id = fopen('my_number.txt', 'w') 
fprintf(file_id, "x = %12.4f\n", x)
fclose(file_id)

This example creates a text file called my_number.txt and opens it for writing (if the file already exists, the original is erased by the fopen command). Once the file is opened, it is assigned an identification number, here called file_id. By using file_id in place of the number 1, the output from fprintf is directed to the file rather than the screen.

For more information about using fprintf, consult the documentation:

doc fprintf

dlmread and dlmwrite

Matlab can read and write delimited data files, which are convenient for passing data between different applications (e.g. spreadsheets). One of the more common delimited formats is the Comma Separated Value (CSV) format, which can be read by nearly every spreadsheet tool. To create a CSV file, we can use the dlmwrite command:

x = [1 2 3; 4 5 6]
dlmwrite('my_matrix.csv',x)

The dlmwrite command created a text file named my_matrix.csv, with these contents:

1,2,3
4,5,6

To read the file back in, use dlmread:

x = dlmread('my_matrix.csv')

In some cases it’s more convenient to use a different delimiter. For instance, tab-delimited data is easier to read and is required by some tools. To make a tab-delimited data file:

x = [1 2 3; 4 5 6]
dlmwrite('my_matrix.tab', x, '\t')

The extra argument, \t, tells the dlmwrite function to use a tab character to separate columns of data. The file contents look like this:

1   2   3
4   5   6

To read the file back in, we use the extra \t argument with dlmread:

x = dlmread('my_matrix.tab','\t')

Plotting

There are hundreds of ways to plot data in Matlab. Here are just a few.

plot command

The simplest way to make a plot is

x = 0:0.1:2
y = x.^2
plot(x,y)

This makes a basic cartesian plot. we can also give it a title, label the axes, and provide a grid:

title('A Simple Plot')
xlabel('x')
ylabel('y')
grid on

You can also plot multiple lines with the same plot command:

x = 0:0.1:2
y = x.^2
z = x.^3
plot(x,y,x,z)

The above example plots \(x^2\) and \(x^{2.5}\) together on the same axes. Now that there are multiple lines on the plot, it makes sense to add a legend:

legend('x squared', 'x cubed')

You can also specify position for the legend:

legend('x squared', 'x cubed', 'Location', 'Southeast')

The possible locations are Southeast, Southwest, Northeast, and Northwest. There are lots of other ways to use the legend command, run doc legend to get the full details.

stairs

For digital data, it is sometimes useful to visualize data points using a stairs plot, which displays the data in discrete steps, like a staircase.

x = 1:10;
y = x.^2;
stairs(x,y)

semilogx, semilogy, loglog

Some data needs to be plotted on a logarithmic scale. To do this, we have three commands:

Example:

x = 0:0.5:4
y = 10.^x
semilogy(x,y)
grid on
x = 2.^(0:10)
y = log(x)
semilogx(x,y)
grid on

figure

The figure command, by itself, pops up a new figure window so that you can make multiple plots. It also supports creating numbered figures, as in figure(1), figure(2) and so on. When writing scripts, it’s a good idea to use numbered figures that you always get the same output.

close

The close command applies to figure windows. For instance, close(1) will destroy figure 1. A more drastic use is close all which will erase all figure windows. When writing scripts, it is a good idea to close figures at the start of the script so that your output won’t be affected by whatever you were doing previously.

hold

You can overlay successive plot commands by activating the hold feature:

x = 0:0.25:4
y = x.^2
z = x.^2.5
figure(1)
plot(x,y)
hold on
plot(x,z)

subplot

You can arrange multiple plots within a figure by using the subplot command. Suppose we want to plot two functions of x, but in separate plots:

x = 0:0.25:4
y = x.^2
z = x.^3
figure(1)
subplot(2,1,1)
plot(x,y)
subplot(2,1,2)
plot(x,z)

The above example creates a plot of y directly above a plot of z

Making Readable Plots

When making plots to use in reports, publications or other professional documents, it’s important that they look nice and are easy to read and understand. It’s also good practice to create plots using a script that can be repeated and modified over time, since documents undergo several stages of editing and revision.

Some useful additions to any plot script are:

For most commands, the font size can be adjusted by adding a “FontSize” property to the command, like this:

title('A Simple Plot','FontSize',22)
xlabel('x','FontSize',22)
ylabel('y','FontSize',22)

The FontSize property can be added to the title, xlabel, ylabel and legend commands to fine-tune their appearance. For axis tick labels, you need to set properties of the axis class by using the gca command like this:

ax = gca;
ax.FontSize = 16;

To precisely control the figure size along with its dimensions and placement on the screen, you can set renderer properties at the time the figure is created:

f = figure(1)
set(f,'Renderer', 'painters', 'Position', [10 10 900 600])

The above example creates figure 1, with upper-left corner at (10,10) and (width,height) equal to (900,600) pixels on the screen.

To adjust the line width in a Matlab plot, just add the LineWidth property to the plot command:

plot(x,y,'LineWidth'1.5)

Trigonometric, Exponential and Logarithmic Functions

In electronic circuits, we frequently encounter functions like sin(x), tan(x), e^x, and polynomials like a*x^2 + b*x + c. Matlab has all that stuff.

sin, cos, and pi

The functions sin(x) and cos(x) assume x is in radians. To convert from degrees to radians, the built-in constant pi can be used. Suppose we want to compute sin(x) where x is 60 degrees. There are 180 degrees in pi radians, so we can make a simple conversion:

sin(60*pi/180)

Let’s make a signal with a frequency f=1kHz with a sample period ts=1 micro-second (us). We’ll generate samples for four periods of the signal.

f = 1e3;           % 1kHz
T = 1/f;           % Signal period (s)
ts = 1e-6;         % Sample period (s)
t = 0:ts:4*T;      % Sample time vector
y=sin(2*pi*f*t);   % Signal sample vector
plot(t,y)          % Plot of signal

exp and log

The functions exp(x) and log(x) implement e^x and ln(x), the ‘natural’ exponential and logarithm, respectively.

x=0:0.1:3;
y=exp(x);
z=log(x);
plot(x,y,x,z)

log10

The base-10 logarithm is obtained using the log10 function. This is especially important for obtaining decibel figures:

x = 1200;
x_dB = 20*log10(x)

Bode Plots and Transfer Functions

Matlab has vast capabilities for analyzing signals and systems. Here we will only scratch the surface. For basic electronic circuits and systems, we will encounter transfer functions with one to three poles. Most of the time, we will be working with low-pass transfer functions.

If we know the pole frequencies and the DC (i.e. zero Hz) magnitude, we can define a transfer function using the Zero/Pole/Gain (ZPK) method, implemented by the zpk function in Matlab. This method specifies a transfer function in this format:

         (s - z(1)) * (s - z(2)) * ... * (s - z(m))
H = k * --------------------------------------------
         (s - p(1)) * (s - p(2)) * ... * (s - p(n))

for a system with m zeros and n poles.

Low-Pass System

For a Low-Pass system with no zeros, two poles, and a DC magnitude of 1000, we typically use the transfer function format shown below.

For hand analysis, we often use the alternative standard form:

                            1
H = A * --------------------------------------------------
         (1 - s/p(1)) * (1 - s/p(2)) * ... * (1 - s/p(n))

This predicts a DC magnitude of A. The constant k is related to A by the expression k = A*p(1)*p(2)*...*p(n).

In Matlab syntax, this is:

p = -[1e3 1e5];  % Pole frequencies
A = 1000;        % Peak magnitude
k = A*prod(p);   % ZPK gain

(There can be some confusion since the term “gain” is variously used to refer both to A and to k. For circuit design, A is the one we care about, and k is just computed to create zpk models.)

With this conversion, we can produce a transfer function and Bode plot as follows:

% Zero frequencies (rad/s)
z = [];

% Pole frequencies (rad/s)
p = -[1e3 1e5];

% DC magnitude:
A  = 1000;

% System model:
k = A*prod(p);
H = zpk(z,p,k)
bode(H)

High-Pass System

For a High-Pass system with one zero, one pole, and a peak magnitude of 1000, the transfer function is

             s
H = k * ------------
         (s - p(1)) 

In this system, the peak magnitude occurs as s goes to infinity. Hence k is the peak magnitude, so A=k.

% Zero frequencies (rad/s)
z = [0];

% Pole frequencies (rad/s)
p = -[1e3];

% Peak magnitude:
A  = 1000;

% System model:
k = A;
H = zpk(z,p,k)
bode(H)

Band-Pass System

For a Band-Pass system with one zero, two poles, and a peak magnitude of 1000, the lower-frequency pole is effectively canceled by the zero. But at higher frequencies, it behaves like a low-pass system, so the relationship between k and A is similar to the low-pass case, but with the lowest pole canceled:

% Zero frequencies (rad/s)
z = [0];

% Pole frequencies (rad/s)
p = -[1e3 1e5];

% Peak magnitude:
A  = 1000;

% System model:
k = A*prod(p)/p(1);
H = zpk(z,p,k)
bode(H)

Matlab for Electrical Engineering

Matlab is a powerful software suite useful for nearly all aspects of an electrical/computer engineer’s professional work. It is one of the most widely used programming languages in the ECE field. It’s like a combination of a calculator, a programming language, and a data analysis tool.

In-App Documentation

Matlab opens in a Command Window and gives you a command prompt. At this prompt, you can access in-terminal documentation for any command by using the help command. For example, we can request help for the disp command:

help disp

To access Matlab’s full documentation window, you can use the doc command like this:

doc disp

The help command is useful for getting fast information whereas the doc command is more in-depth, often with examples and tutorials.

Matlab Scripts: [name].m

A Matlab program is called a script, which means it is a sequence of commands that you could type into the command window. The script is interpreted rather than compiled. Matlab interprets one line at a time while the script is being run. For simple calculations, it’s convenient to type straight into the command window. For more complex programs, or for programs that need to be repeatable, you should write a script.

Matlab scripts conventionally end with a .m file type. You can create and edit scripts directly within the command window by clicking New Script in the menu bar.

For ECE courses, you are encouraged to prepare your homework solutions in Matlab scripts. By using scripts, your reasoning is clearly documented and it becomes easier to correct errors and reuse methods.

Comments

Comments in Matlab begin with a %. It is helpful to add comments throughout script files to clarify what’s intended. A comment can be placed inline, like this:

x = 2; % Setting x to 2

In this tutorial, we will sometimes use inline comments like this, but you are not required to type the comments as you work through the example commands.

Functions

A Matlab script can be used to define a new command with the same name as the file. For example, look at the top of the window for the “New” button and click it. A text editor should open with a blank page. Type these lines:

% my_function.m
% By:   [Your Name]
% Date: [The Current Date]
%
% Description:
%   Inputs:  x (scalar)
%   Outputs: y (scalar)
%
% Computes y = 2x
%

function y = my_function(x)

y = 2*x;

end % my_function

Once you’ve typed the lines above, click “Save” and save it with the name my_function.m. Then, in the Matlab command window, run the function:

x = 2;
y = my_function(x)

When you define a function, the heading provides help text. This is crucial if you intend to share your function with others, or if you want to use the script again in the future (you might forget what it does).

help my_function

Private functions

You can define multiple functions within a script file, but only one function can be accessed by users (the function name must match the file name). Any other functions can be accessed only from within the script file.

Edit the my_function.m file and make these changes:

    function y = my_function(x)

    y = private_function(x);

    end % my_function
    
    
    function y = private_function(x)
    
    y = 2*x;
    
    end % private_function

Save the file, then in the command window you can run my_function(x) but not private_function(x).

x = 2;
my_function(x)

Functions with Multiple Outputs

A function can support multiple outputs using this syntax:

function [y, z] = my_function(x)

y = 2*x;
z = 3*x;

end % my_function

Modify my_function.m to return y=2x and z=3x. Then save it and run it at the prompt.

[y,z] = my_function(x)

Matlab Syntax

If you are new to Matlab, begin by entering all the example lines shown below, one at a time, into the command window. This is so you can build some experience with how Matlab works and what it can do for you.

Variables

By default, every variable in Matlab is a vector or matrix of double-precision floats. Variables are declared and defined in a single statement:

x = 2

The above statement creates a variable named x with a value of 2.00. We can use x as a scalar value, but Matlab also treats it as a vector of length 1.

To declare a vector with multiple elements, type a list of numbers inside square brackets:

x = [2 4 5 4 2]

We can also declare an empty vector:

x = []

And we can concatenate values to incrementally fill up the vector:

x = [x 2]
x = [x 4]
x = [x 5 4 2]

Matlab also has a useful sequence notation:

x = 1:10 
x = 0:2:10

In general, a sequence is declared by three numbers separated by colons as start:step:end. You can also concatenate a sequence with other vector entries:

x = [1:1:8 9 10]

A matrix is defined by using a semi-colon or carriage return to separate the rows:

x = [1 2 3; 4 5 6]
x = [7 8 9
    10 11 12]

Vector and matrix variables are indexed from 1, going from top-to-bottom and then left-to-right. Matrix elements can be selected using a single index value, or using Cartesian indices as (row,column):

x = [1 2 3; 4 5 6]
x(1)
x(2)
x(1,1)
x(1,3)

You can also use sequence indexing to extract sub-vectors and submatrix ranges:

x = [1 1 2 3 5 8 13 21]
x(1:3)
x(1:2:8)

Another example:

x = [1:4; 5:8; 9:12]
x(2,:)
x(:,2)
x(2:3,2:3)

It is also often useful to transpose a matrix using the symbol:

x = [1 2 3]'

Matrix Algebra

Matlab’s real strength lies in matrix operations. You can directly multiply two matrices if they have compatible dimensions:

x = [1 2 3
     4 5 6]
y = [1 2
     3 4
     5 6]
x*y
y*x

You can also multiply a vector into a matrix in the usual way:

x = [1 2 3
     4 5 6]
y = [1 2] 
y*x

And you can add vectors or matrices:

x = [1 2 3]
y = [4 5 6]
x+y

You can also build a matrix by the product of two vectors:

x = [1 2 3]
y = [1
     2
     3]
y*x

Looping and Conditionals

For Loops

A Matlab for-loop is initiated using the for keyword, and the loop scope is terminated by an end statement as in this example:

x = 1:100
for idx=1:5
   disp(x(idx))
end

While Loops

The while-loop below does the same thing as the for-loop example.

x   = 1:100
idx = 1;

while (idx < 6)
   disp(x(idx))
   idx = idx + 1;
end

If-Else

x = 2;
y = 0;

if (x > 1) 
   disp('true')
   y = 1;
else
   disp('not true')
end

Vectorized Operations and Functions

In addition to conventional looping and branching constructs, it is often much faster to use vector and matrix functions. A few important examples are listed here. As a rule, Matlab programs will run much faster if vectorized functions are used instead of loops.

Termwise operators .* and .^

You can multiply two vectors term-by-term:

x = [1 2 3 4]
y = [2 2 1 1]
x.*y

Similarly you can exponentiate all terms of a vector:

x = [1 2 3 4]
x.^2

You can also termwise-multiply two matrix variables:

x = [1 2 3; 1 2 3; 1 2 3]
y = [2 2 2; 2 2 2; 2 2 2]
x.*y

And you can termwise-multiply a vector with a matrix. In this instance, the vector is applied to all the rows in the matrix:

x = [1 1 1; 1 1 1; 1 1 1]
y = [1 2 3]
x.*y

find

The find command performs a search to find elements that satisfy a condition:

x = 2:2:10
find(x==4)

In the above example, find returns the index of the matching element, which appears at index 2. Suppose we search for something that doesn’t exist:

find(x==5)

In this case, the find command returns an empty array.

When there are multiple matches, the find command returns a vector containing all the matching indices.

find(x>5)

returns [3 4 5]. If only the first K matches are desired, find can be provided an additional argument:

find(x>5,2)

returns [3 4], and

find(x>5,1)

returns the scalar value 3.

One of the most common applications of the find command is to apply a command across all matching entries. For example:

x(find(x>5)) = 5

returns [2 4 5 5 5]. In human language, this statement says “find all elements of x that are greater than 5, and set them equal to 5.”

sum

The sum command adds together all elements in a vector, or all rows in a matrix. Examples:

x = [1 1 1 1 1 1]
sum(x)

This returns 6. Next, a matrix example:

x = [1 1 1; 1 1 1]
sum(x)

This returns [2 2 2]. Now, a transposed maxtrix example:

x = [1 1 1; 1 1 1]
sum(x')

This returns [3 3] since it sums across the columns of x.

cumsum

The “cumulative sum” function, abbreviated as cumsum, computes the incremental summation over a vector. The result is essentially a discrete integral. In the example below, we provide a square function, and use cumsum to “integrate” the square:

x = [1 1 1 1 -1 -1 -1 -1]
cumsum(x)

The result is [1     2     3     4     3     2     1     0], a triangle function, which is the expected piecewise-linear integral of a square step function.

diff

The diff function computes the pairwise difference between neighboring elements in a vector. This is similar to a discrete derivative:

x = [0 1 2 3 4 3 2 1 0]
diff(x)

This returns [1     1     1     1    -1    -1    -1    -1], making it the inverse of the cumsum function.

movsum

This command computes a sliding window sum of width K:

K=2
x = 1:10
movsum(x,K)

This returns [1   3   5   7   9  11  13  15  17  19], i.e. it returns 0+x(1), x(1)+x(2), x(2)+x(3), and so on.

max, min

These return the maximum and minimum values in a vector. They do not return the positions of max or min values.

x = 1:10
max(x)
min(x)

abs

The absolute value or complex magnitude of all elements in a vector.

x = -10:10
abs(x)

Input and Output

Matlab excels at plotting, but we will begin with simpler text I/O commands.

fprintf

The fprintf command can be used to write text to a file or to the command window. The command below writes “hello world” to the command window:

fprintf(1, "hello world\n")

In this example, the first argument is the number 1, which instructs Matlab to write output into the command window rather than to a file.

The Matlab fprintf function is based on the C fprintf function. It has the same capability for formatted output. This example writes a numerical value to the command window:

x=3
fprintf(1, "The value of x is %d\n", x)

Several of the C % codes are supported. Here are some of the more important ones:

code type
%d decimal integer
%x hexadecimal integer
%d octal integer
%f floating point number
%e scientific notation
%g compact scientific
%s string

You can also add parameters to control how numbers are displayed. For example, we can control how many digits are allowed on the left and right side of the decimal point:

x = 13.75
fprintf(1,"x = %12.4f\n", x)

In the example above, the “12” instructs the function to display the number in exactly 12 characters. The “.4” indicates that there should be four digits after the decimal point, and the “f” indicates a floating point number.

For printing text to a file, you first need to open the file using the fopen command. Then use fprintf to write text into the file, and finally close the file with fclose. Here is an example:

x = 13.75
file_id = fopen('my_number.txt', 'w') 
fprintf(file_id, "x = %12.4f\n", x)
fclose(file_id)

This example creates a text file called my_number.txt and opens it for writing (if the file already exists, the original is erased by the fopen command). Once the file is opened, it is assigned an identification number, here called file_id. By using file_id in place of the number 1, the output from fprintf is directed to the file rather than the screen.

For more information about using fprintf, consult the documentation:

doc fprintf

dlmread and dlmwrite

Matlab can read and write delimited data files, which are convenient for passing data between different applications (e.g. spreadsheets). One of the more common delimited formats is the Comma Separated Value (CSV) format, which can be read by nearly every spreadsheet tool. To create a CSV file, we can use the dlmwrite command:

x = [1 2 3; 4 5 6]
dlmwrite('my_matrix.csv',x)

The dlmwrite command created a text file named my_matrix.csv, with these contents:

1,2,3
4,5,6

To read the file back in, use dlmread:

x = dlmread('my_matrix.csv')

In some cases it’s more convenient to use a different delimiter. For instance, tab-delimited data is easier to read and is required by some tools. To make a tab-delimited data file:

x = [1 2 3; 4 5 6]
dlmwrite('my_matrix.tab', x, '\t')

The extra argument, \t, tells the dlmwrite function to use a tab character to separate columns of data. The file contents look like this:

1   2   3
4   5   6

To read the file back in, we use the extra \t argument with dlmread:

x = dlmread('my_matrix.tab','\t')

Plotting

There are hundreds of ways to plot data in Matlab. Here are just a few.

plot command

The simplest way to make a plot is

x = 0:0.1:2
y = x.^2
plot(x,y)

This makes a basic cartesian plot. we can also give it a title, label the axes, and provide a grid:

title('A Simple Plot')
xlabel('x')
ylabel('y')
grid on

You can also plot multiple lines with the same plot command:

x = 0:0.1:2
y = x.^2
z = x.^3
plot(x,y,x,z)

The above example plots \(x^2\) and \(x^{2.5}\) together on the same axes. Now that there are multiple lines on the plot, it makes sense to add a legend:

legend('x squared', 'x cubed')

You can also specify position for the legend:

legend('x squared', 'x cubed', 'Location', 'Southeast')

The possible locations are Southeast, Southwest, Northeast, and Northwest. There are lots of other ways to use the legend command, run doc legend to get the full details.

stairs

For digital data, it is sometimes useful to visualize data points using a stairs plot, which displays the data in discrete steps, like a staircase.

x = 1:10;
y = x.^2;
stairs(x,y)

semilogx, semilogy, loglog

Some data needs to be plotted on a logarithmic scale. To do this, we have three commands:

Example:

x = 0:0.5:4
y = 10.^x
semilogy(x,y)
grid on
x = 2.^(0:10)
y = log(x)
semilogx(x,y)
grid on

figure

The figure command, by itself, pops up a new figure window so that you can make multiple plots. It also supports creating numbered figures, as in figure(1), figure(2) and so on. When writing scripts, it’s a good idea to use numbered figures that you always get the same output.

close

The close command applies to figure windows. For instance, close(1) will destroy figure 1. A more drastic use is close all which will erase all figure windows. When writing scripts, it is a good idea to close figures at the start of the script so that your output won’t be affected by whatever you were doing previously.

hold

You can overlay successive plot commands by activating the hold feature:

x = 0:0.25:4
y = x.^2
z = x.^2.5
figure(1)
plot(x,y)
hold on
plot(x,z)

subplot

You can arrange multiple plots within a figure by using the subplot command. Suppose we want to plot two functions of x, but in separate plots:

x = 0:0.25:4
y = x.^2
z = x.^3
figure(1)
subplot(2,1,1)
plot(x,y)
subplot(2,1,2)
plot(x,z)

The above example creates a plot of y directly above a plot of z

Making Readable Plots

When making plots to use in reports, publications or other professional documents, it’s important that they look nice and are easy to read and understand. It’s also good practice to create plots using a script that can be repeated and modified over time, since documents undergo several stages of editing and revision.

Some useful additions to any plot script are:

For most commands, the font size can be adjusted by adding a “FontSize” property to the command, like this:

title('A Simple Plot','FontSize',22)
xlabel('x','FontSize',22)
ylabel('y','FontSize',22)

The FontSize property can be added to the title, xlabel, ylabel and legend commands to fine-tune their appearance. For axis tick labels, you need to set properties of the axis class by using the gca command like this:

ax = gca;
ax.FontSize = 16;

To precisely control the figure size along with its dimensions and placement on the screen, you can set renderer properties at the time the figure is created:

f = figure(1)
set(f,'Renderer', 'painters', 'Position', [10 10 900 600])

The above example creates figure 1, with upper-left corner at (10,10) and (width,height) equal to (900,600) pixels on the screen.

To adjust the line width in a Matlab plot, just add the LineWidth property to the plot command:

plot(x,y,'LineWidth'1.5)

Trigonometric, Exponential and Logarithmic Functions

In electronic circuits, we frequently encounter functions like sin(x), tan(x), e^x, and polynomials like a*x^2 + b*x + c. Matlab has all that stuff.

sin, cos, and pi

The functions sin(x) and cos(x) assume x is in radians. To convert from degrees to radians, the built-in constant pi can be used. Suppose we want to compute sin(x) where x is 60 degrees. There are 180 degrees in pi radians, so we can make a simple conversion:

sin(60*pi/180)

Let’s make a signal with a frequency f=1kHz with a sample period ts=1 micro-second (us). We’ll generate samples for four periods of the signal.

f = 1e3;           % 1kHz
T = 1/f;           % Signal period (s)
ts = 1e-6;         % Sample period (s)
t = 0:ts:4*T;      % Sample time vector
y=sin(2*pi*f*t);   % Signal sample vector
plot(t,y)          % Plot of signal

exp and log

The functions exp(x) and log(x) implement e^x and ln(x), the ‘natural’ exponential and logarithm, respectively.

x=0:0.1:3;
y=exp(x);
z=log(x);
plot(x,y,x,z)

log10

The base-10 logarithm is obtained using the log10 function. This is especially important for obtaining decibel figures:

x = 1200;
x_dB = 20*log10(x)

Bode Plots and Transfer Functions

Matlab has vast capabilities for analyzing signals and systems. Here we will only scratch the surface. For basic electronic circuits and systems, we will encounter transfer functions with one to three poles. Most of the time, we will be working with low-pass transfer functions.

If we know the pole frequencies and the DC (i.e. zero Hz) magnitude, we can define a transfer function using the Zero/Pole/Gain (ZPK) method, implemented by the zpk function in Matlab. This method specifies a transfer function in this format:

         (s - z(1)) * (s - z(2)) * ... * (s - z(m))
H = k * --------------------------------------------
         (s - p(1)) * (s - p(2)) * ... * (s - p(n))

for a system with m zeros and n poles.

Low-Pass System

For a Low-Pass system with no zeros, two poles, and a DC magnitude of 1000, we typically use the transfer function format shown below.

For hand analysis, we often use the alternative standard form:

                            1
H = A * --------------------------------------------------
         (1 - s/p(1)) * (1 - s/p(2)) * ... * (1 - s/p(n))

This predicts a DC magnitude of A. The constant k is related to A by the expression k = A*p(1)*p(2)*...*p(n).

In Matlab syntax, this is:

p = -[1e3 1e5];  % Pole frequencies
A = 1000;        % Peak magnitude
k = A*prod(p);   % ZPK gain

(There can be some confusion since the term “gain” is variously used to refer both to A and to k. For circuit design, A is the one we care about, and k is just computed to create zpk models.)

With this conversion, we can produce a transfer function and Bode plot as follows:

% Zero frequencies (rad/s)
z = [];

% Pole frequencies (rad/s)
p = -[1e3 1e5];

% DC magnitude:
A  = 1000;

% System model:
k = A*prod(p);
H = zpk(z,p,k)
bode(H)

High-Pass System

For a High-Pass system with one zero, one pole, and a peak magnitude of 1000, the transfer function is

             s
H = k * ------------
         (s - p(1)) 

In this system, the peak magnitude occurs as s goes to infinity. Hence k is the peak magnitude, so A=k.

% Zero frequencies (rad/s)
z = [0];

% Pole frequencies (rad/s)
p = -[1e3];

% Peak magnitude:
A  = 1000;

% System model:
k = A;
H = zpk(z,p,k)
bode(H)

Band-Pass System

For a Band-Pass system with one zero, two poles, and a peak magnitude of 1000, the lower-frequency pole is effectively canceled by the zero. But at higher frequencies, it behaves like a low-pass system, so the relationship between k and A is similar to the low-pass case, but with the lowest pole canceled:

% Zero frequencies (rad/s)
z = [0];

% Pole frequencies (rad/s)
p = -[1e3 1e5];

% Peak magnitude:
A  = 1000;

% System model:
k = A*prod(p)/p(1);
H = zpk(z,p,k)
bode(H)