This is an old revision of the document!
The MATLAB Guide shows a list of common MATLAB commands that will be helpful is completing assignments. Click on any subject on the list to be taken directly to the material or scroll down. Some sections are composed of multiple subsections: related assignments, external resources, and description. The first subsection consists of links that will take you assignments that are related to the MATLAB topic. External Resources consists of links that will take you to other places on the internet that you might find helpful in learning the material. The last section is a basic description of the subject followed by syntax and examples.
The following link is a great site to go to for more information on any topic in the guide. Just type the topic in the search bar. MathWorks Documentation
MATLAB is a numerical computation computer software. All of the data types are matrices that can either represent numeric or string variables. It is also case sensitive (i.e. 'b' is not the same as 'B').
When you open up MATLAB you have three basic windows available: Current Folder, Command Window, and Workspace.
The Current Folder window informs the user what folder MATLAB is currently working out of, and displays all of the files located withing that folder. The Command Window prompts the user for input by the » symbol. Once the user provides inputs, variables are created and shown in the Workspace.
PDF by JOHN O. ATTIA see page 17
MATLAB provides easy access to help by using the function help. You can type in help in the Command Window in order to access a list of categories. To bypass the list and get information on a specific topic you can type in help followed by a the specific name of a function as shown in the example below.
help cos
MATLAB will display information about the specific function. If you typed in help cos you should see the following.
>> help cos
cos Cosine of argument in radians. %% First line
cos(X) is the cosine of the elements of X. %% Second line
See also acos, cosd. %% Third line
Overloaded methods:
codistributed/cos
gpuArray/cos
sym/cos
Reference page in Help browser
doc cos
The first couple of lines shows the name of the function and a description of the function. In this case if tells you that cosine requires the argument to be in radians and not degrees. It also shows you the syntax of the function. Type in other functions to get a feel for it.
PDF by JOHN O. ATTIA see pages 18 -19
The basic data object in MATLAB is a matrix. Scalars can be thought of as a 1×1 matrix. Arrays can be thought of
as a 1Xn or nX1 matrix, and a matrix can assume the size mxn, nxm, or nxn. MATLAB has no type declaration or dimension statement. All memory allocation is done automatically, and can by dynamic i.e. you can easily change the
size of any variable. The basic syntax is shown below.
variable = expression
A matrix can be created using the form shown below.
A = [1,2,3,
4,5,6,
7,8,9]
When you hit enter, MATLAB will display the matrix.
A =
1 2 3
4 5 6
7 8 9
To suppress this, you can add a semicolon at the end of any statement.
A = [1,2,3,
4,5,6,
7,8,9];
The commas aren't necessary, and can be replaced by spaces.
A = [1 2 3
4 5 6
7 8 9];
You can also indicate a new row using the semicolon instead of placing the code on different lines.
A = [1 2 3; 4 5 6;7 8 9];
You can create a 1xn matrix by following the code below.
B = [1 2 3];
You can create a 1×1 matrix by following the code below. Notice how the brackets [ ] are not needed in the statement.
C = 1;
Often you will want the transposition of a matrix. The syntax is
variable_name followed by a ' symbol.
Using the matrix A created above, the example below creates the transpose and assigns it to a new variable.
>> C = A'
C =
1 4 7
2 5 8
3 6 9
>>
If you want to get the size of a matrix you can use the size function. This function will return the number of rows and columns in the matrix.
>> size(A)
ans =
3 3
Length returns the number size of the largest dimension. If row > column then it will return the length of the row. If column > row then it will return the length of the column.
>> length(B)
ans =
3
>> length(B')
ans =
3
The command who will display all of the variables in the workspace.
>> who Your variables are: A B C ans
The command whos will display all of the variables in the workspace along with certain information. See the image below.
>> whos Name Size Bytes Class Attributes A 3x3 72 double B 1x3 24 double C 3x3 72 double ans 1x1 8 double
You can also single out a specific variable.
>> whos A Name Size Bytes Class Attributes A 3x3 72 double
MATLAB stores all of the variables in the workspace, and will not delete them until you command it to. To clear all of the variables type in clear in the Command Window. To clear a single variable you can postscript the name of the variable after the clear command.
>> clear B >> clear
At this point all of your variables should have been deleted.
| class | Assignment | Topic |
|---|---|---|
| 240 | HW 3 | Inverse Matrix |
PDF by JOHN O. ATTIA see pages 21-22
The common matrix operations are additions(+), subtraction (-), multiplication(*), transpose('), and two types of division(/,\).
For the explanations of Matrix Operations we will use the following two matrices.
A = [1 2 3; 4 5 6; 7 8 9]; B = [9 8 7; 6 5 4; 3 2 1];
The rules for addition and subtraction are the same. You can either add/subtract a scalar(1×1 matrix) to a matrix or another matrix(nxm matrix) to another matrix as long as their dimensions agree.
>> A + 1
ans =
2 3 4
5 6 7
8 9 10
>> A + B
ans =
10 10 10
10 10 10
10 10 10
You can multiply a scalar and a matrix together, or you can multiply two matrices together provided that
their inner two operands are the same. i.e. n1xm1 * m1xn1. Notice how the two inner operands are the same
(m1 = m2).
>> 2*A
ans =
2 4 6
8 10 12
14 16 18
>> B*A
ans =
90 114 138
54 69 84
18 24 30
Division follows the same rules as multiplication. The difference is that there are two operators (/,\). The first operator A/B is equivalent to 2/4 = 0.5. While A\B is equivalent to 4/2 = 2.
>> A/B
ans =
0.6667 0 -1.6667
1.1667 0 -2.1667
1.6667 0 -2.6667
>> B/A
ans =
-2.6667 0 1.6667
-2.1667 0 1.1667
-1.6667 0 0.6667
Sometimes you will need to use the inverse of a matrix. The command inv does this for you. In the case you have A*C = B and you know A and B but not C, you can rewrite the equation as C = inv(A)*B.
>>C=inv(A)*B C = -20.0000 -22.0000 -19.0000 44.0000 46.0000 39.0000 -14.0000 -15.0000 -15.5000
For efficiency you might want to pre-allocate memory for a matrix so the program doesn't have to constantly reallocate memory as the size of the matrix changes. To accomplish this there are two commands that you can use.
ones(rows, cols) will create a nxm matrix and fill it with ones.
>> E = ones(4,5)
E =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
>>
zeros(rows, cols) will create a nxm matrix and fill it with zeros.
>> F = zeros(4,5)
F =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
PDF by JOHN O. ATTIA see pages 23 - 25
Array operations refer to element by element operations. For element by element multiplication and division this is indicated by a '.' in front of '*,/,\'. Addition and subtraction are the same for matrix and array operations. All of the array operands are (*,/,\,^). Consider the following two arrays.
A = [1 2 3]; B = [4 5 6];
I can multiply the 1-nth element in array A with the 1-nth element in array B. That is the 1st element in array A will be multiplied by the 1st element in array B, the second element in array A will be multiplied by the second element in array B and so on until the nth element in array A is multiplied by the nth element in array B.
>> A.*B
ans =
4 10 18
Division is similar.
>> A./B
ans =
0.2500 0.4000 0.5000
The '^' operator is the the raising to the power operator.
>> B.^A
ans =
4 25 216
PDF by JOHN O. ATTIA see pages 25 - 27
The characters 'i' and 'j' have been reserved in MATLAB to indicate complex numbers. However, it is possible to assign 'i' and 'j' to some other value. To ensure that MATLAB always interprets the complex numbers correctly it is a good idea to place a 1 before 'i' or 'j' as in '1i' or '1j'. Even if you reassign 'i' and 'j' by using '1i' and '1j' MATLAB will treat it as a complex number. Examine the code to see the subtle differences. Notice that as long as you don't use any operands between the number and the complex symbol 'i' or 'j' MATLAB will interpret it as a complex number even if you reassign 'i' or 'j'.
>> y = 4 +2j
y =
4.0000 + 2.0000i
>> y = 4 + 2*j
y =
4.0000 + 2.0000i
>> j = 2
j =
2
>> u = 4 +2j
u =
4.0000 + 2.0000i
>> u = 4 + 2*j
u =
8
>> u = 4 + 2*(1j)
u =
4.0000 + 2.0000i
There are commands in MATLAB that manipulates complex numbers or grabs a certain portion of a complex number. The
real and imaginary commands isolates and grabs the real and imaginary part of a complex number.
For demonstrations purposes let's use a variable u with value 4 +2i.
real(u) - isolates and grabs the real part of u.
img(u) - isolates and grabs the complex part of u. It does not carry the i or j because it is understood
that it is complex
>> u = 4 + 2i;
>> real(u)
ans =
4
>> img(u)
ans =
2
>> r = real(u) % you can also store the sub-part of u in another variable
r =
4
Indexing_2 this is more advance
Indexing a certain element in a matrix is slightly different in MATLAB than other standard languages. Indexing in MATLAB begins at 1 and not 0. If you try to index the 0 element you will get an error. We will first examine 1xn matrices and then mxn matrices.
1xn matrices require only one number for indexing since MATLAB knows that there is only one row associated with the
matrix. To index an element in a matrix the syntax is
variable_name(element_number_to_index)
The code below gives you an example.
>> A= [1 2 3];
>> A(1)
ans =
1
You can also index multiple elements at once, and groups of multiple elements at once. When you index multiple
elements or groups of elements you are essentially creating another matrix composed of the elements in the first
matrix. Below is the syntax and examples for different ways to create different matrices.
variable_name([first_index last_index])
1xn matrix
variable_name([first_index1 last_index1, first_index2 last_index2])
mxn matrix
variable_name([first_index1 last_index1; first_index2 last_index2])
>> A([1 2]) % Index two elements that form one group.
ans =
1 2
>> A([1 2, 2 3]) % Index two different groups. The comma indicates a 1xn matrix.
ans =
1 2 2 3
>> A([1 2; 2 3]) % Index two different groups. The semicolon indicates a mxn matrix.
ans =
1 2
2 3
>>
Indexing with mxn matrices is a little more complicated since you have to indicate the row and column you
are indexing. The basic syntax is
variable_name(row_index, column_index).
Notice how there is a coma separating the row_index and column_index. It is also possible to index groups of elements. The syntax for this is
variable_name([row_index_first row_index_last] (, or ;) [column_index_first column_index_last])
>> B = [1 2 3; 4 5 6; 7 8 9]
B =
1 2 3
4 5 6
7 8 9
>> B(1,1)
ans =
1
>> B([1 2], [1 2])
ans =
1 2
4 5
PDF by JOHN O. ATTIA see pages 27-30
Colon Symbol see 0-6:00
The colon symbol is a powerful operator in MATLAB. It can be used to (1) create matrices, (2) index subgroup of matrices, and (3) perform iterations.
(1) create matrices.
Often you will want to create a large array with specific increments. An example of this would be an array that
represents time. You create this array by indicating the starting number and the last number separated by a ':'.
MATLAB will create an array beginning from the starting number and increment by 1 until it reaches the last
number.
variable_name = first_number:last_number
>> t = 1:10
t =
1 2 3 4 5 6 7 8 9 10
Sometimes you will want to specify the specific increment interval.
Variable_name = first_number:increment interval:last_number
>> t = 0:0.002:0.01
t =
0 0.0020 0.0040 0.0060 0.0080 0.0100
>> t = [(1:1:4);(5:1:8)]
t =
1 2 3 4
5 6 7 8
(2) create sub-matrices When the colon is used to index it indicates all the rows or columns.
>> t(:,1) %Indicates all of the rows in the first column.
ans =
1
5
>> t(1,:) %Indicates the first row and all of the columns
ans =
1 2 3 4
>> t(:) % creates a column vector
ans =
1
5
2
6
3
7
4
8
PDF by JOHN O. ATTIA see page 31
MATLAB allows you to create files in which you can organize related code and save it for later. The two types of files are Script Files and Function Files.
PDF by JOHN O. ATTIA see pages 31-32
Script Files are especially useful when you are creating a project that requires multiple lines of code. Instead of running each line of code over again in the command window, you can run a script file which will automatically run every line of code written in it. This makes editing code really easy.
To create a Script File click on the “New Script” button located on the upper left portion of the MATLAB window.
To run the script, click on the green arrow locate in the upper middle portion of the MATLAB window. By clicking on it, if the script is not already saved, it will prompt you to save it before running it. If you are not currently working in the folder to which you saved the script, MATLAB will prompt you to change folders. If your script is empty the command window should only show the name of your script file. You can also run your script file by typing the name of the script in the command window and pressing enter.
Enter the following code in the script file and run it.
t = 0:0.1:10-0.1; %time span signal = cos(pi/5*t); half_signal = signal(1:length(t)/2); %signal for half a period plot(t,signal, t(1:length(t)/2), half_signal+0.1); %plots the signals
Function files are similar to functions created is other standard languages as c, c++, etc. The allow you to organize lines of code that performs a generic function that can be used multiple times by calling it.
To create a function file is similar to creating a script file. The difference is that on the first line of the
script you have declare it a function by writing “function” and then stating the return variables, function
name, and the parameters the function takes. The parameters are what variables the user passes into the function
and the return variables are what the function gives back after executing the code. MATLAB allows the user to have
multiple return and parameter variables. When you save the function file, the name of the file must be the name
of your function_name else MATLAB will not recognize it as a function and it will not run.
function [return1, return2, return_t] = function_name(param1, param2, param3)
% The function computes the sum, multiplication, and subtraction of the % three variables passed in. function [sum, multiplication, subtraction] = Arithmetic(param1, param2, param3) sum = param1 + param2+param3; multiplication = param1*param2*param3; subtraction = 0 - param1 - param2-param3;
The syntax to call a function is
[return1, return2, return_t] = function_name(param1, param2, param3)
MATLAB does not do name association when passing variables between function, rather it using place association. Using the above function, return1 will be assigned the value of sum, return2 the value of multiplication and so on.
>> [s,m,sub] = Arithmetic(1,2,3)
s =
6
m =
6
sub =
-6
MATLAB offers many great features that allows the user to represent numbers graphically. The user can create bar, 2D, 3D, and other types of graphs. MATLAB also allows the user to label their graph, add titles and legends, adjust the axis and much more.
Plot see 0-1:30.
The basic graph is the plot function which allows the user to plot a 2D graph.
plot(y) - plots the elements of y as a function of their index. i.e. the first element of y will be
associated with the value of 1 along the x axis.
plot(x,y) -plots the elements of y and associates them with the elements of x. i.e. the first element of y
will be associated with the 1 element of x. The size of X must be the same size as Y.
plot(x1,y1,x2,y2) - plots multiple sets of data on the same graph.
plot(x1,y1,'s1',x2,y2,'s2') -s1 and s2 allows the user to customize the appearance of the line. This
parameter is indicated by surrounding parentheses. By omitting the 's' parameter, MATLAB will use the default
settings.
The following code is taken from MATLAB (help plot)
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star (none) no line
y yellow s square
k black d diamond
w white v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
For example, plot(X,Y,'c+:') plots a cyan dotted line with a plus
at each data point; plot(X,Y,'bd') plots blue diamond at each data
point but does not draw any line.
Axis Control see 3:30-4:00.
Matlab allows you to change the view of the plot figure. Some basic commands are described below.
axis([Xmin Xmax Ymin Ymax]) -sets the axis limit to the indicated range.
axis([ 0 5 -10 10]);
xlim([Xmin Xmax]) -sets the x axis to the indicated range.
ylim([Ymin Ymax]) -sets the y axis to the indicated range.
Annotations see 1:30-2:00.
Annotation increases the readability of the graph. You can add a title, legend, and axis labels.
title('insert_title_here') -gives the graph a title.
xlabel('insert_label_here') -gives the x axis a label such as time.
ylabel('insert_label_here') -give the y axis a label such as Voltage.
text(x,y,'string') -generates text at the indicated x y coordinate
The legend helps to distinguish between multiple lines displayed in the graph.
legend('name_of_first_line_displayed', 'name_of_second_line_displayed',…,'nth_name')
The order of the names must match the order the data was entered into the plot function. For example if you created the plot, plot(x_data1, y_data1, x_data2,y_data2), then you would create a legend by coding, legend('name_of_data1', 'name_of_data2').
Figures are created to display images in MATLAB. Every time a plot is created MATLAB automatically generates a figure in which it displays the plot. MATLAB allows you to control some features of figures: assigning a certain plot to a certain figure, clearing a figure, and plotting multiple plots in the same figure.
To assign a certain plot to a figure first specify the figure.
figure(figure_number)
Then add the plot function.
figure(1); plot(Y);
If you have two plot statement after a figure statement, only the last plot will be displayed in the figure window.
figure(1); plot(Y1); plot(Y2); % only the second plot is displayed in the figure
To fix the problem mentioned above the user can either: indicate a different figure for each plot or use the
hold command.
hold on -causes all subsequent plots to be displayed in the same figure
hold off -prevents all subsequent plot to be displayed in the same figure
figure(1); % data Y1 and Y2 are displayed in figure 1 plot(Y1); hold on; plot(Y2); hold off; figure(2); % data Y3 is displayed in figure 2 plot(Y3);
Exponential, Natural and Common log see all
Semi-log see 2:20 -4:00
MATLAB can generate plots using a logarithmic scale for either the x-axis, y-axis or both. The use of these
commands are similar to those of plot. It is common to use these commands when creating a bode plot. It should be noted that the logarithm of negative numbers do not exist, so the data must be positive when using these commands.
loglog(x,y) -plots the x and y data using a logarithmic scale.
semilogx(x,y) -plots the x-axis on a logarithmic scale.
semilogy(x,y) -plots the y-axis on a logarithmic scale.
%plots the gain of an active filter constructed using an
%op amp in terms of decibles as a function of frequency
Vout = [ 10 30 50 50 50 30 10]; %output voltage of an op amp
Vin = [1 1 1 1 1 1 1]; %input voltage
f = [1 1e1 1e2 1e3 1e4 1e5 1e6];
db = 20*log10(Vout./Vin);
figure(1);
subplot(2,2,1);
loglog(f,db);
xlabel('frequency Hz');
ylabel('Voltage in Db');
title('log-log')
subplot(2,2,2);
semilogx(f,db);
xlabel('frequency Hz');
ylabel('Voltage in Db');
title('semilog-x');
subplot(2,2,[3,4]);
semilogy(f,db);
xlabel('frequency Hz');
ylabel('Voltage in Db');
title('semilog-y');
MATLAB support both common logarithmic calculations and natural logarithmic calculations. The commands for these can sometimes be confusing.
log(x) -calculates the natural logarithm of x.
log10(x) -calculates the common logarithm of x.
exp(x) -exponential function
Polar see 6:00-7:00. I recommend the entire video.
A polar plot shows the a graphical depiction of the relationship between an angle and a magnitude.
polar(theta, M,S) -theta is the angle in radiant, M is the magnitude, and S is the style of the line.
S is
not necessary.
% A complex number can be represented as a phase and a magnitude. Z = r + j % can be represented as |Z|e^(j*theta) with |Z| being the magnitude and % theta being the phase from 0 degrees. Z = 4 + 3j; % the complex number M = sqrt(4^2 + 3^2); % the magnitude of the complex number theta = atan(3/4); % the phase from the horizontal axis polar(theta,M,'*b');
Mesh watch all of it.
Mesh creates a 3D graph by plotting a function of two variables.The function is a 3D matrix, mxnxp, and the
two variable are arrays that do not have to have the same number of elements in each array.
mesh(x,y,z)
x and y are the variables of the function, and z is the output of the function.
%The rate of decay can be simulated by a exponential function of the form
%e^(-t/tau) with t being time and tau being the time constant.
t = 0:1e-2:1; % an array that represents time from 0 to 1 second with an interval length
% o 10ms
tau = [1e-3, 1e-2, 1e-1, 1]; % an array of multiple taus.
f = zeros(length(tau),length(t)); %allocates memeory for the 3D matrix
f(1,:) = exp(-t/tau(1)); % the function e^(-t/tau) for all taus and ts
f(2,:) = exp(-t./tau(2));
f(3,:) = exp(-t./tau(3));
f(4,:) = exp(-t./tau(4));
figure(1);
mesh(t,tau,f); %mesh plot
xlabel('time');
ylabel('tau');
zlabel('f(tau,time)');
subplot see 4:10-5:00.
The subplot command divides up an image window into sub-sections, which allows a different graph to be
displayed in each different sub-sections.
subplot(m,n,p)
m indicates the number of rows and n indicates the number of columns that divides the image
window into m rows and n columns. P indicates in which sub-sections the image will be displayed.
subplot(2,3,1); %divides the image window into 2 rows and three columns. The next graph will be displayed in %section 1. %| s1 | s2 | s3 | %| s4 | s5 | s6 | plot(x1); % this plot will be displayed in section 1 (s1). subplot(2,3,2); %using the same image window the selected section is s2. plot(x2); % this plot will be displayed in section 2 (s2). %It is possible to have a graph spread over multiple sections. subplot(2,2,[4,5,6]); %The next graph will spread over sections s4, s5 and ,s6.
For another example of subplot look at the section titled Logarithmic.
MATLAB has various control statements that simplifies repetitious code or differentiate between actions. The popular control statements are the if-statements, while, and for loop. The functionality for the three mentioned statements are the same as in other programming languages, they only differ in syntax.
Control statements use comparative statements to determine when to perform or stop a certain action. The rational and logical operators are described below. You will notice that they are familiar to other programming languages, but there are some subtle differences.
| Rational Operators | Meaning |
|---|---|
| < | less than |
| ⇐ | less than or equal |
| > | greater than |
| >= | greater than or equal |
| == | equal |
| ~= | not equal |
| Logical Operators | Meaning |
| & | and |
| ! | or |
| ~ | not |
PDF by JOHN O. ATTIA see pages 56 - 61
If-Statement video see 0:45 - 4:00 for basic concept.
If-statements compares data with specific cases, and the case in which the data fall determines the next statement
of code that will be executed. The general from of an if-statement is provided below.
if logical expression 1
statement group1
elseif logical expression 2
statement group 2
elseif logical expression 3
statement group 3
elseif logical expression 4
statement group4
else
statement group 5
end
MATLAB will test each logical expression in sequential manner starting with the first, and working down the list to the last logical expression. The first logical expression that is true will be executed and the statement group that pertains to the logical expression will be executed. After executing the statement, the rest of the if-statement segment will be skipped. i.e. only one statement will ever be executed at most.
It is not necessary to have to include elseif or else segments in the if-statement. The minimum is the 'if' part.
The following are also valid if-statements.
if logical expression 1
statement group1
else
statement group 2
end
or
if logical expression 1
statement group1
end
MATLAB also allows for nested if-statements.
if logical expression 1
if logical expression 1-a
statement group1-a
else
statement group 1-b
end
else
if logical expression 2-a
statement group2-a
else
statement group 2-b
end
end
The following segment of code is an example of an if-statement.
% Sets a min and max limit. This can be used for op-amps to simulate
%clipping.
Vpos = 20; %The positive rail of the op amp
Vneg = -20; %The negative rail of the op amp
G = -5; % The gain of the op amp.
Vin = 5; % The input of the op-amp.
Vout = G*Vin; % The calculation of Vout without taking into account
% clipping
%The if statement takes into account clipping by comparing Vout to
% the rails. If Vout is beyond the range of the rails then it will be
% given the value of the rail that it was origninaly beyond. If Vout
% is within the range of the rails, nothing will happend.
if Vout > Vpos %Checks to see if it passes the upper rail
Vout = Vpos;
elseif Vout < Vneg %Checks to see if it passes the lower rail
Vout = Vneg;
else
% do nothing. It is within range
end
PDF by JOHN O. ATTIA see pages 54 - 56
For-loop The first two minutes shows the basics. The rest gives a good detailed description for those struggling with the concept of for-loops.
For-loops repeats a segment of code for a specified number of iterations. The basic form is shown below.
for index = expression
statement group X
end
index is the variable used as a counter. The expression indicates the range of iterations, and the size of each
increment. The basic syntax of the expression is
m:n
m is the beginning of the range and n indicates the end. The size of each increment is 1. It is possible to change
the size of each increment by including it into the expression.
m:p:n
p tells MATLAB the size of each increment.
The following code gives examples of possible expressions.
0:10; %the expression begins at zero and increments by one until it reaches 10. % The for-loop will execute while the index takes on the values: 0,1,2,3,4,5,6,7,8,9,10. % In this specific case the for-loop will execute 11 times. 0:0.5:10; %the expression begins at zero and increments by 0.5 until it reaches 10.
It is popular to use for-loops when you need to step through or index an array. Below is an example of a for-loop.
% This program creates a square-wave with a period of 10.
t = 0:30; % an array that represents time.
Thalf = 5; % the length of half a period
T = 10; % length of a period
counter = 0; % keeps track of the number of seconds passed. It is used
% to indicate when to go high or low on making the square wave.
square_wave = zeros(1,length(t)); % allocates memory for the square wave
for t = 0:30 % I can use time as the index. the variabel t will be
% re-written as a scalar and not an array.
if counter < Thalf
square_wave(t+1) = 1; %high poriton of square wave
counter = counter + 1; % increments the counter
elseif counter < T
square_wave(t+1) = 0; % low portion of square wave
if counter == 9
counter = 0; % resets the counter
else
counter = counter +1;
end
end
end
plot(square_wave); % the square wave isn't perfect
It is also possible to have nested for loops just like nested if-statements.
for index_1 = expression_1
statement group X
for index_2 = expression2
statement group 2
end
end
PDF by JOHN O. ATTIA see pages 61 - 63
While-loop video see 0:00 - 2:00 for basic information.
While loops are very similar to for-loops, except while loops do not repeat the same segment of code for an
indicated number of times. Rather, it repeats the same segment of code until a certain condition is met that must
be triggered by the code inside the while loop. The basic form of the while-loop is shown below.
while expression 1
statement group 1
end
statement group 2
If expression 1 is true the program will jump into the while loop and execute statement group 1. Afterwards it will return to expression 1 and evaluate if again to verify that it is still true. If it is still true, statement group 1 will execute again. This cycle continues until expression 1 is false. When expression 1 is false statement group 1 will no execute, and the program will exit the while loop and continue onto statement group 2. In order for the program to ever leave the while-loop statement group 1 must affect expression 1 so that it becomes false. A simple example is shown below.
% This code will fill an array up with ones.
length_of_array = 10;
array_to_be_filled = zeros(1,length_of_array);
x = 1; % counter for the while loop.
while x <= length_of_array
array_to_be_filled(x) = 1; % fills the array with ones.
x = x +1; % This code affect the expression, and will eventually
% trigger the exist of the while-loop.
end
It is also possible to do nested while-loops in MATLAB.
while expression 1
while expression 1-a
statement group 1-a
end
statement group 1-b
end
statement group 2
| class | assignments | topic |
|---|---|---|
| 240 | HW 9 | Roots |
MATLAB offers a variety of commands that interact with polynomials.
Roots see 0:30-1:00
The roots command returns the roots of a polynomial that is a variable in vector form.
r = roots(p)
p is a vector containing n+1 polynomial coefficients starting with the highest to the lowest.
For example, p = [1 9 18] is equivalent to 1x^2 + 9x + 18.
>> p = [1 9 18];
>> r = roots(p);
r =
3 6
MATLAB allows the users to create, and modify files of various types. The files can contain numbers or strings.
Opens up the file specified by the file name.
Syntax:
variable_name = fopen(FILENAME,PERMISSION); opens the file FILENAME in the mode specified by PERMISSION:
'r' open file for reading
'w' open file for writing; discard existing contents
'a' open or create file for writing; append data to end of file
'r+' open (do not create) file for reading and writing
Type 'help fopen' in the command window of matlab for more details.
Reads data from an open text file
Syntax:
A = fscanf(variable_name,formatSpec);
Example: File count.dat contains three columns of integers. Read the values in column order,
and transpose to match the appearance of the file:
fid = fopen('count.dat');
A = fscanf(fid,'%d',[3,inf])';
fclose(fid);
Type 'help fscanf' in the command window of matlab for more details
Closes the file
Syntax:
fclose(file_name); closes the file_name
fclose('all'); close all the files open
It's important to do this whenever you do fopen
Play an array as sound
Syntax
sound(Y,FS); sends the signal in array Y (with sample frequency FS) out to the speakers
Example:
load handel
sound(y,Fs)
You should hear a snippet of Handel's Hallelujah Chorus.
Type 'help sound' in the command window for more details
Increases the Sample rate by an integer factor.
Syntax:
y = interp(x,r); This increases the sampling rate of x (input signal) by a factor of r.
Example:
Create a sinusoidal signal that is sampled at 1kHz. Upsample by 6 t = 0:0.01:1; x = sin(2*pi*30*t) y = interp(x,6);
Type 'help interp' in command window of matlab for more details.