Introduction to MATLAB - Agricultural & Applied Economics

advertisement
Agricultural and Applied Economics 637
Introduction to MATLAB
The Fundamentals
I believe the best way to really learn econometrics is to go inside the black box.
As such for the next couple of days we will develop “native” computer code used
to estimate parameters of the classical regression model (CRM) and calculate
associated regression-based statistics. We have found that the MATLAB software
package is a very useful tool for obtaining an understanding of applied
econometrics as it allows you to directly translate what is presented in class from
theoretical perspective into an operational software program. This software has
been used extensively by econometricians. This is the third year that I will be
using this software having used the GUASS software system since the early
1980’s. I (and you) will be using this software exclusively in AAE637 for those of
you taking the class except for the final paper where you can use any software of
your choosing.
The best way to start learning MATLAB is to use it.1 This document will take you
through a basic introduction of the software system and hopefully familiarize you
with the structure of the programming language. You’ll want to save your code
when you are finished, as we’ll build on it over the next few days. Be aware: the
steps outlined here are just one way of doing things. There are many many ways to
edit, run, code, etc., with code development being idiosyncratic. In AAE637 you
will be exposed to a variety of methods to undertake estimation and you will
invariably develop your own programming style. Through the years, I have found
a number of strategies that help with the development and debugging of my own
computer code. I will offer these insights to you over the course of your taking
AAE637. I hope you find them useful.
The MATLAB software is a very extensive system that can be used for a variety of
numerical/statistical operations. You will not use all of the features and commands
associated with this program during this course. You will be able to undertake a
variety of basic as well as fairly advanced tasks by the end of the class. I would
1
Note: Like any other capital investment there is depreciation of your human capital year over year. This
depreciation rate increases with the lack of use.
1
recommend that you become familiar with MATLAB via the use of the myriad of
web-based tutorials. The MATLAB resources section of the class website contains
a few of these resources. Do not print this material out without looking at the
document(s) as some of the PDFs are more than 500 pages long. I also encourage
you to learn to use the on-line help system available from the main menu once
MATLAB is running.
For those of you wanting to work at home will need to purchase the student version of MATLAB
available from DOIT (http://techstore.doit.wisc.edu/product.asp?itemnum=C61733&login=P )
for $93. Versions for Window$ and Macs are available. This is a great deal as you are
purchasing a permanent license so long as you are registered student at any college or university.
It is a fully functional version of the MATLAB software system. This software is also available
in various computer labs across campus including the AAE lab and the Department’s Remote
server.2
The goal for this workshop is to make sure everyone knows how to get started developing your
own MATLAB code, accessing MATLAB data sets and outputting the results in a readable
format. So let’s get started.
1. LOG INTO THE AAE NETWORK
If you have an AAE account, log in as usual. If you do not have an AAE account you can login
using a guest account using the username and password displayed throughout the HECC lab.
(Please note: guest users are not allowed to access the REMOTE server.)
2. OPEN MATLAB
On the remote/lab computers go to the Start menu → All Programs → Statistics → MATLAB
(Note: If you trying this on your own machine, you will probably have an icon on your Desktop.
You will also probably locate the MATLAB program in a different location than the above.)
When you start MATLAB, the desktop appears, containing tools (graphical user interfaces) for
managing files, variables, and applications associated with MATLAB.
The following illustration shows the default desktop. You can customize the arrangement of
tools and documents to suit your needs. For more information about the desktop tools, refer to
the Desktop Tools and Development Environment section of the help system.
The Department’s remote server is only available to Department of Agricultural and Applied Economics graduate
students. Due to security and administrative reasons, we have a policy of not granting access to non-Departmental
students.
2
2
Command Window: Enter
commands at the
command line, indicated
by the prompt (>>)
Workspace: Explore data that
you create or import from files
Current Folder:
Access your files
Command History: View
or rerun commands that
you entered at the
command line
When the Command Window is open the cursor is blinking at the MATLAB prompt. Here you
can enter commands line-by-line and see your output in the same window. With the command
window highlighted you can clear the Command Window by RMB the window and selecting
Clear Command Window. This clears the screen of any characters. You may see a warning
message asking if this is really what you want to do. You can also enter the command clc in the
command window and then hit the <enter> key to invoke the command.
You can type in the following command in the Command Window:
y=16+15 <then hit the return key> (This adds 16 and 15 and shows the value of y)
Note that with a trailing semicolon no output is shown.
3. WRITING AND RUNNING A MATLAB PROGRAM.
As implied the above, you can undertake various tasks using MATLAB one command at a time
(i.e., interactive mode) or by running a collection of commands at once contained within a single
command file (i.e.; batch mode). To run a file in batch mode you first create an ASCII (or text)
file containing these commands. This is often referred to as a script file. This file can be created
using your own favorite ASCII file editor (e.g., Notepad++, Tedit, etc) or you can use the native
MATLAB program editor. Using the native MATLAB editor is very useful as it checks your
syntax as you create the command file. MATLAB expects all script files containing MATLAB
commands end with an “m” extension. I highly recommend that you follow this convention.
3
Let’s assume that you will be using the MATLAB editor. Once MATLAB
is started click on the New Script icon. This will open up an editor window
where you can write an entire program and run these commands using a
single invoking of the file.
The first example we will use is
contained in the file example_1.m
. This file is contained in the location indicated at the
right:
Click on the icon
to now open the file you want. You should see something like the
following: (Note, the underlined items are native MATLAB commands):
FYI: a few general comments about the code.
 There need not be a semi-colon to end every command. If you have a semi-colon the
result of the command will not be shown.
 If a statement does not fit on one line, use an ellipsis (three periods), ..., followed by the
Enter key to indicate that the statement continues on the next line. A good practice to
adopt is that if your command line is more than 80 characters, continue with your code on
a 2nd line, indent, and keep typing.
 Any variable to the left of an equals sign is a name I made up, e.g. that I want to define
for MATLAB
 Anything to the right of an equals sign is either a variable name I already defined by a
previous command or a MATLAB command/operation/function/reserved word/etc.
 Comments, that don’t impact the operation are located after the “%” . You should adopt
a policy of using comments extensively in your code.
The MATLAB editor has the normal Windows-based file management system so you can edit
and save this file like any other program you have used before if you are a Window$ user (I
assume the same is true for Mac users). I would recommend that you save this file to your
private network directory or your own
removable storage device. In the editor,
save the file by clicking on the following
icon in the Editor tab: and save it in the
desired location.
4
With your cursor located in the MATLAB editor window, run this file by clicking on the
following button located in the editor toolbar,
or simply type the name of the file in the
Command Window and hit the Return key.
What happened? Is the matrix c what you expected it to be?
Now in your edit window, add the following to the end of your program. What do you expect it
to do?
d=a*b
Save the file and run the program again and notice what happens- it doesn’t work. That is, you
receive the error message in the bottom window that looks similar to the following:
If you run the program in batch mode you get the following:
The number in parenthesis provides the line number that generated the error. Although I won’t
go over it here, you may want to learn how to use the program debugger. I will have Sarah
review this material in a later lab.
This new command doesn’t make sense since the “a” and “b” matrices are not dimension
compatible with respect to matrix multiplication. Given the severity of the error MATLAB did
not run the remaining portion of the program after this error. There is a useful message in the
command window, though. When you get this message, it is often helpful to verify the
dimensions of your matrices. You will find the Workspace window very useful for the
debugging of your code. For small arrays, it shows its elements. For larger arrays, it will show
its dimension. By default this window is the box in the upper right of your screen but the
location can be changed or window minimizes depending on your needs. If you click on an array
displayed in the Workspace window the elements of this array is displayed.
The problem with the above MATLAB command “*” performs matrix multiplication, and here
you are telling it to multiply a (2x3) matrix times a (2x3) matrix (which you should remember is
not possible).
Change the last line to read
d=a .* b
5
Also add the line
e=a*bʹ % Note the transpose
Run the code again. Does it work? What is different about these? What do these commands do?
4. READING IN A DATA SET
There are a number of methods for reading in datasets into your MATLAB software. You could
load native MATLAB datasets (and similar to STATA and SAS datasets) that are binary files
that cannot be opened and examined using an ASCII (text) editor. For an overview of how to
open a variety of file types in MATLAB refer to the User’s Guide and the Data Import and
Export section. For these workshops (and for our assignments) we will load Excel files
containing the data. The first row of these files contains the variable names and the remaining
rows are the data. DBMSCOPY is a useful program that can transform any ASCII or binary file
of a particular type (e.g., SAS, STATA, EXCEL, GAUSS) into any other file type. Besides
being able to transform data from one form to another, DBMSCOPY also has the nice
characteristic of allowing you to view any type of data, undertake simple data management
activities and to obtain descriptive statistics of this data. The DBMSCOPY manual is available
on-line. Feel free to use your own data conversion software if you prefer.
In the zip file I previously emailed you contained our first data set. The data set is called
china_00.xls. Unzip this file to your network drive, hard disk or USB storage device.
4.1 Accessing MATLAB Remotely
You can access MATLAB remotely so long as you have internet access and a valid AAE account
(If you have a MAC computer you can also access the remote server but I do not know how to do
this. Talk to the HECC director for more information.) You can use the Remote Desktop
feature of your operating system to connect to the AAE Remote Server. If you are at a remote
location, click on START, then PROGRAMS then ACCESSORIES then COMMUNICATIONS
then REMOTE DESKTOP CONNECTION. The computer you want to access is our remote
servers which have the computer name (address) of: remote.aae.wisc.edu . Once you enter this
address, you will then see what looks like another Windows session. What is actually occurring
is that your remote machine is in fact starting a session on a virtual Windows machine (i.e., the
REMOTE server). You can then log-in to the remote computer using your AAE username and
password. The remote machine is set up exactly (or very similar to) the regular AAE lab
machines. This means that you have access to all the programs in the AAE lab from your remote
location. Since you are logging in using your AAE account, you have the same drive mappings
as you have when you log into a lab machine. This means that so long as your data, programs
etc are stored on a network resource, you have access to it from your remote location. In
addition if you set the remote access options correctly on your home machine you can access not
only the network drives but also your local drives. Refer to the HECC help system for assistance
(http://www.hecc.wisc.edu/).
4.2 MATLAB Code for Reading in a Dataset
Now, I would like you to use the 2nd MATLAB command file to illustrate the use of MATLAB,
example_2.m. In the MATLAB editor close the previously used MATLAB command file (Note:
6
You can have multiple files open at once if desired). Then open up the file example_2.m in the
editor The following is a listing of the commands in this file (MATLAB functions in bold).
clear;
% Command to clear memory
clc;
% Command to clear the command window
[full_data,varnames,raw] = xlsread('china_00');
%{
Load all data from an excel dataset
variables: fafh, region, fah, percinc
%}
fafh = full_data(:,1);
region = full_data(:,2);
fah = full_data(:,3);
percinc = full_data(:,4);
[numobs,numvars]=size(full_data); % Determine the number of rows
delete('w:\example_1.out')
% Deletes a previously created output file
diary('w:\example_1.out');
% Open up a txt file for output
diary off;
% Turn off the sending of output to the output file
var_names=char('fafh','region','fah','percinc');
% var_names is a (4 x 1) character array
disp 'I have successfully run the program'
% Show this text in the command window
This block of text, or something very similar to it, will be needed at the beginning of virtually all
of your MATLAB programs.
What do the above commands do?
clear: A MATLAB command clears the workspace from previous batch runs or
command line inputs (http://www.mathworks.com/help/techdoc/ref/clear.html).
clc: A MATLAB command that clears the command window
(http://www.mathworks.com/help/techdoc/ref/clc.html)
xlsread: Command to read in a Microsoft Excel spreadsheet file. There are a number of
different structures of this command. Below is a listing of these alternative structures
obtained from the xlsread help entry:
[num,txt,raw] = xlsread(filename)
[num,txt,raw] = xlsread(filename,sheet)
[num,txt,raw] = xlsread(filename,range)
[num,txt,raw] = xlsread(filename,sheet,range)
[num,txt,raw] = xlsread(filename,-1)
[num,txt,raw] = xlsread(filename,sheet,'','basic')
[num,txt,raw,custom] = xlsread(filename,sheet,range,'',functionHandle)
The command [num,txt,raw] = xlsread(filename) reads data from the first worksheet
in the Microsoft Excel spreadsheet file named filename and returns the numeric data
in array num (this can be any name I want). With this command structure, it
optionally returns the variable names in the cell array txt (this can be any name I
7
want), and the unprocessed data (numbers and text) in cell array raw (this can be any
name I want). (http://www.mathworks.com/help/techdoc/ref/xlsread.html)
fafh: Created variable containing the (numobs x 1) vector of food away from home
expenditures
region: Created variable containing the (numobs x 1) vector of region of residence
fah: Created variable containing the (numobs x 1) vector of food at home expenditures
percinc: Created variable containing the (numobs x 1) vector of per capita income
size: Returns the dimension of the target matrix in separate variables numobs (rows) and
numvars (columns). (http://www.mathworks.com/help/techdoc/ref/size.html)
numobs: A created variable (this can be any name I want) that contains the number of
observations in the dataset
numvars: A created variable (this can be any name I want) that contains the number of
variables in the data matrix
delete: This command is used to delete the named file. If the file does not exist you will
receive an error (nonfatal) message.
(http://www.mathworks.com/help/techdoc/ref/delete.html)
diary: Is used to write a copy of all subsequent keyboard input and the resulting output
(except it does not include graphics) to the named file, where the filename is the full
pathname or filename is in the current MATLAB folder. If the file already exists,
output is appended at the end of the file. By deleting it first I avoid the appending of
output. (http://www.mathworks.com/help/techdoc/ref/diary.html)
diary off: This command suspends the diary command. (Note that diary on resumes
diary mode using the current filename, or the default filename diary if none has yet
been specified.)
5. RUN THE CODE, AND CHECK TO MAKE SURE YOU HAVE
SUCCESSFULLY LOADED THE DATA
With the above program in the editor, run this file using the main editor menu. In the Workspace
area you should see the four vectors of data plus the underlying matrix each with 2050
observations. You should see the following displayed in the Command window: “I have
successfully run the program”.
6. IDENTIFY YOUR VARIABLES
8
The variables in this data set are the following
Description
Variable Name
Per Capita Income
percinc
At home food expenditures
fah
Away from home food expenditures
fafh
Region (either 1, 2, or 3)
region
The use of the “ : ” in the above command file (e.g., lines 9 – 12) tells MATLAB to grab all the
rows of the full data matrix for the particular column of data . If you wanted to grab only the
120th -220th observations for some reason you would type the following:
inc_2 = full_data(120:220,4); or inc_2 = percinc(120:220,:);
If you want to create a (2050 x 2) matrix containing per capita income and region you could
enter the following either in your command file or interactively:
income_region=full_data(:,[4 2]);
This would grab the 4th and 2nd columns (the columns associated with PERCINC and REGION)
from the full_data matrix using all the observations (which is what the “:” means). I could have
created this new variable via the horzcat horizontal concatenation command:
income_region = horzcat(percinc,region);
Note that one can only use horizontal concatenation if the two matrices have the same number of
rows. The resulting file will have the sum of the number of columns of the component matrices.
(Note, vertical concatenation can be obtained via the use of the vertcat command. In this case to
undertake vertical concatenation one needs the same number of columns in the candidate
matrices)
In the command window type the following command:
begind=numobs-10;
test_data=horzcat(fah(begind:numobs,:),region(begind:numobs,:)) ;
and see what is generated.
FYI: The parentheses attached to the end of a matrix name allow you to specify part of a matrix.
For example,
full_data(2,4) is the single element in the 2nd row and 4th column of the full_data matrix
full_data(2,1:3) is the (1x3) vector of element in the 2nd row and 1st through 3rd
columns
full_data(:,4) generates the vector of elements in the entire 4th column of full_data.
7. NOW LET’S DO SOME MATHEMATICAL MANIPULATIONS AND
DATA INTERPRETATION
Let’s do the following simple tasks:
9
i) What is the average income and food expenditure?
ii) What is the maximum level of income?
iii) What percent of households live in region 1?
iv) What is the minimum, maximum, and average food away from home expenditures in
region 1?
****************************************************************
7.A ADDITIONAL COMMANDS YOU FIND USEFUL
A list of commands by category can be obtained from the following URL:
http://www.mathworks.com/help/matlab/functionlist.html . An alphabetical list can be obtained
via the following: http://www.mathworks.com/help/matlab/functionlist-alpha.html . Here are a
few commands that you may find useful:
sum(x) returns the sum of the elements in matrix x
(http://www.mathworks.com/help/techdoc/ref/sum.html)
cumsum(x) returns the cumulative sum of the columns (or rows) of matrix x
(http://www.mathworks.com/help/techdoc/ref/cumsum.html)
mean(x) returns the mean of every column (or row) of matrix x
(http://www.mathworks.com/help/techdoc/ref/mean.html)
std(x) returns the standard deviation of the elements in each column (or row) of matrix x
(http://www.mathworks.com/help/techdoc/ref/std.html)
min(x) returns the smallest element in each column (or row) of matrix x
(http://www.mathworks.com/help/techdoc/ref/min.html)
max(x) returns the largest element in each column (or row) of matrix x
(http://www.mathworks.com/help/techdoc/ref/max.html)
cov(x) computes the variance-covariance matrix
(http://www.mathworks.com/help/techdoc/ref/cov.html)
zeros(r,c) creates a matrix with r rows and c columns full of zeros
(http://www.mathworks.com/help/techdoc/ref/zeros.html)
ones(r,c) creates a matrix with r rows and c columns full of ones
(http://www.mathworks.com/help/techdoc/ref/ones.html)
eye(N) creates an NxN idendity matrix (you must either use a number in place of N or define N)
(http://www.mathworks.com/help/techdoc/ref/eye.html)
randn(r,c) creates a matrix with r rows and c columns of c independent std. normal random
numbers
(http://www.mathworks.com/help/techdoc/ref/randn.html)
sort(x) Sort array elements in ascending or descending order depending on the additional
arguments supplied when using this command
(http://www.mathworks.com/help/techdoc/ref/sort.html)
size(x) returns array dimensions
(http://www.mathworks.com/help/techdoc/ref/size.html)
normcdf(x) returns the Prob(z<=x) where z is a N(0,1) random variable (requires Statistics
Toolbox)
10
%{ , %} The text enclosed within the %{ and %} symbols is a comment block. Use these
symbols to insert comments that take up more than a single line in your script of
function code. Any text between these two symbols is ignored by MATLAB. You can
use these to have MATLAB not execute a set of commands.
7.B. Logical Expressions
&, |, ~ Element by element logical operations on arrays
Syntax: expr1 & expr2
expr1 | expr2
~expr
The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. These
operators are commonly used in conditional statements, such as if and while, to determine
whether or not to execute a particular block of code. Logical operations return a logical
array with elements set to 1 (true) or 0 (false), as appropriate.
expr1 & expr2 represents a logical AND operation between values, arrays, or expressions
expr1 and expr2. In an AND operation, if expr1 is true and expr2 is true, then the AND of
those inputs returns a true value. If either expression is false, the result is false. Here is a
pseudocode example of AND:
IF (expr1: all required inputs are included) AND ...
(expr2: all inputs are valid)
THEN (result: execute the function)
expr1 | expr2 represents a logical OR operation between values, arrays, or expressions expr1
and expr2. In an OR operation, if expr1 is true or expr2 is true, then the OR of those inputs
returns a value of true. If both expressions are false, the result is false. Here is a pseudocode
example of the use of OR:
IF (expr1: S is a string) OR ...
(expr2: S is a cell array of strings)
THEN (result: parse string S)
~expr represents a logical NOT operation applied to expression expr. In a NOT operation, if
expr is false, then the result of the operation is true. If expr is true, the result is false. Here is
a pseudocode example of NOT:
IF (expr: function returned a Success status) is NOT true
THEN (result: throw an error)
The function xor(A,B) implements the exclusive OR operation.
eq Test for equality
11
Syntax: A == B
eq(A, B)
A == B compares each element of array A for equality with the corresponding element of
array B, and returns an array with elements set to logical 1 (true) where A and B are equal,
or logical 0 (false) where they are not equal. Each input of the expression can be an array
or a scalar value.
If both A and B are scalar (i.e., 1-by-1 matrices), then the MATLAB software returns a
scalar value.
If both A and B are nonscalar arrays, then these arrays must have the same dimensions, and
MATLAB returns an array of the same dimensions as A and B.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it
were an array having the same dimensions as the nonscalar input array. In other words, if
input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5
matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as
the nonscalar input array.
When comparing handle objects, use eq or the == operator to test whether objects are the
same. Use isequal to test if objects have equal property values, even if those objects are
different.
eq(A, B) is called for the syntax A == B when either A or B is an object.
gt Test for greater than
Syntax: A > B
gt(A, B)
A > B compares each element of array A with the corresponding element of array B, and
returns an array with elements set to logical 1 (true) where A is greater than B, or set to
logical 0 (false) where A is less than or equal to B. Each input of the expression can be an
array or a scalar value.
If both A and B are scalar (i.e., 1-by-1 matrices), then the MATLAB software returns a
scalar value.
If both A and B are nonscalar arrays, then these arrays must have the same dimensions, and
MATLAB returns an array of the same dimensions as A and B.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it
were an array having the same dimensions as the nonscalar input array. In other words, if
input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5
matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as
the nonscalar input array.
12
gt(A, B) is called for the syntax A>B when either A or B is an object.
ge Test for greater than or equal to
Syntax: A >= B
ge(A, B)
A >= B compares each element of array A with the corresponding element of array B, and
returns an array with elements set to logical 1 (true) where A is greater than or equal to B,
or set to logical 0 (false) where A is less than B. Each input of the expression can be an
array or a scalar value.
If both A and B are scalar (i.e., 1-by-1 matrices), then the MATLAB software returns a
scalar value.
If both A and B are nonscalar arrays, then these arrays must have the same dimensions, and
MATLAB returns an array of the same dimensions as A and B.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it
were an array having the same dimensions as the nonscalar input array. In other words, if
input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5
matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as
the nonscalar input array.
ge(A, B) is called for the syntax A >= B when either A or B is an object.
le Test for less than or equal to
Syntax: A <= B
le(A, B)
A <= B compares each element of array A with the corresponding element of array B, and
returns an array with elements set to logical 1 (true) where A is less than or equal to B, or
set to logical 0 (false) where A is greater than B. Each input of the expression can be an
array or a scalar value.
If both A and B are scalar (i.e., 1-by-1 matrices), then the MATLAB software returns a
scalar value.
If both A and B are nonscalar arrays, then these arrays must have the same dimensions, and
MATLAB returns an array of the same dimensions as A and B.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it
were an array having the same dimensions as the nonscalar input array. In other words, if
input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5
matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as
the nonscalar input array.
13
le(A, B) is called for the syntax A < =B when either A or B is an object.
lt Tests for less than
Syntax: A < B
lt(A, B)
A < B compares each element of array A with the corresponding element of array B, and
returns an array with elements set to logical 1 (true) where A is less than B, or set to logical
0 (false) where A is greater than or equal to B. Each input of the expression can be an array
or a scalar value.
If both A and B are scalar (i.e., 1-by-1 matrices), then the MATLABsoftware returns a
scalar value.
If both A and B are nonscalar arrays, then these arrays must have the same dimensions, and
MATLAB returns an array of the same dimensions as A and B.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it
were an array having the same dimensions as the nonscalar input array. In other words, if
input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5
matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as
the nonscalar input array.
lt(A, B) is called for the syntax A < B when either A or B is an object.
ne Test for inequality
Syntax: A ~= B
ne(A, B)
A ~= B compares each element of array A with the corresponding element of array B, and
returns an array with elements set to logical 1 (true) where A and B are unequal, or logical
0 (false) where they are equal. Each input of the expression can be an array or a scalar
value.
If both A and B are scalar (i.e., 1-by-1 matrices), then the MATLAB software returns a
scalar value.
If both A and B are nonscalar arrays, then these arrays must have the same dimensions, and
MATLAB returns an array of the same dimensions as A and B.
If one input is scalar and the other a nonscalar array, then the scalar input is treated as if it
were an array having the same dimensions as the nonscalar input array. In other words, if
input A is the number 100, and B is a 3-by-5 matrix, then A is treated as if it were a 3-by-5
matrix of elements, each set to 100. MATLAB returns an array of the same dimensions as
the nonscalar input array.
14
ne(A, B) is called for the syntax A ~= B when either A or B is an object.
C. Use of FOR LOOPS
The following illustrates the use of a “For Loop”. You should refer to your reference material
for instructions concerning its use. It is very important to remember that the use of the For loop
can make your life much easier if you are doing repetitive tasks. The For loop is designed to
execute statements a specified number of times.
x=zeros(20,1);
%{This initializes the x matrix so there are place holders for later use In
general this only needs to be done when using for or do loops.%}
for i =1:20;
%{ i is an temporary variable used to control the loop In this example
the loop goes from 1 to 20 in increments of 1, e.g., 20 steps %}
x(i)=i;
/* the ith element of the vector x is assigned the current value of i */
end;
/* end of for loop */
Another way to accomplish the above (without creating a placeholder for “x”):
for i = 1:20;
if i == 1;
x=i;
else; x=vertcat(x,i); /* This vertically concatenates the previous x vector with
another element equal to the current value of “i” */
end;
end;
If I wanted every odd value of x to be 0, I could have done the following:
x=zeros(20,1);
for i =1.0: 2, 20;
x[i]=i;
end;
or
x=zeros(20,1);
for i = 1:10;
jj=(2*i);
x[jj]=jj;
end;
D. RUN THE DEMO_MATLAB PROGRAM
Now you are ready to run a longer MATLAB program. I sent you a 3rd command file with the
name demo_matlab.m . I assume you have either saved it in your network drive or in your USB
storage device. This file undertakes some basic matrix manipulations. After examining this file,
run it in MATLAB and make sure you understand the various operations.
A FINAL NOTE: Try to develop a habit of writing clean and neat code (e.g.
use of indentation for loops, lines of code that don’t go on forever, etc). This
will facilitate code debugging.
15
Indenting code makes reading statements, such as for (do while) loops, easier. To set and apply
indenting preferences to code in the Editor:
1) From the main program toolbar choose Preferences > Editor/Debugger > Language
2) From the Language drop-down menu, select a language
3) Select or clear Apply smart indenting while typing, depending on whether you want
indenting applied automatically, as you type. If you clear this option, you can manually
apply indenting by selecting the lines in the Editor to indent, right-clicking, and then
selecting Smart Indent from the context menu.
4) Do one of the following:
a. If you chose any language other than MATLAB in step 2, click OK.
b. If you chose MATLAB in step 2, select a Function indenting format, and then
click OK. Function indent formats are:
i. Classic: The Editor aligns the function code with the function declaration.
ii. Indent nested functions: Editor indents function code within a nested function.
iii. Indent all functions — The Editor indents the function code for both main and
nested functions.
16
Download