MATLAB Intro Ravichandran
MATLAB Intro Ravichandran
1.
There are two windows that you can type stuff into in Matlab: The editor
and the command window. Knowing how to use these windows can make
coding and debugging your programs much less painstaking.
As the name suggests, the command window is where you enter
instructions for Matlab to perform. It is handy to know a few basic
commands so that you can instruct Matlab to perform basic functions.
Listed are some functions, which I find very handy to make moving
around the Command Window much easier. Make sure that you try these
functions out and are accustomed to them.1
Note that the words that are to be typed into Matlab are in a different font than the explanatory
texts.
Variables
A Matlab variable is essentially a tag that you assign to a value while that
value remains in memory. The tag gives you a way to reference the value
in memory so that your programs can read it, operate on it with other
data, and save it back to memory. Variables will be the essential dynamic
medium, which your program will access, change and produce data. In
the following example, the >> sign shows what I have typed in the
command window.
For instance:
>> monkey = 8
monkey =
8
Now that you have taught Matlab that monkey = 8, every time
you type in monkey, Matlab will understand that you are talking
about the number 8 (until you enter clear, which clears the
memory of all variables).
>> 2*monkey
ans =
16
I find the use of an analogy very helpful to drive this concept home. Take
the above example. We first enter monkey = 8. Now imagine that the
variable on the left of the equal sign is a little box and that you are storing
the stuff on the right into the variable on the left. You can never swap this
order, unlike what you might be used to doing in math.
Anytime you call the variable thereafter, you call for the value stored
inside. However, you can change the contents of the box by reassigning
the variable (putting or taking out stuff from the box). For example,
monkey = monkey + 1. Here Matlab will understand that you are
assigning a new variable monkey (a value of 9) by using the old value of
monkey, which is 8. Reassigning variables like this will come very much in
handy when we deal with for-loops.
You can also assign a variable to be an array2. We will look at
manipulating arrays in another section.
Changing the name of variables is usually redundant but can be done if
you type it in the following format: new_name = monkey. Now new_name
will have a value of 8.
Note that Matlab will throw back the value of the variable unless you end
the line with a semi colon, ;. Always remember to do this especially
when working on lengthy pieces of code.
Also remember that Matlab variable names must begin with a letter,
which may be followed by any combination of letters, digits, and
underscores. Matlab distinguishes between uppercase and lowercase
characters, so A and a are not the same variable.
When naming a variable, make sure you are not using a name that is
already used as a function name, either one of your own functions or one
of the functions in the Matlab language. If you define a variable with a
function name, you will not be able to call that function until you either
remove the variable from memory with the clear function. For example,
if you enter the following command, disp = 5, you will not be able to use
the Matlab disp function until you clear the variable with clear disp.
3.
Editor window
The Editor window is very different from the command window because
here you can make all the mistakes you want and Matlab will never shout
at you. It is best to code in the editor window and run the program in the
command window. Avoid coding in the command window, as it will be a
huge pain to write programs like that.
The advantage of coding in the editor window is that Matlab tells you
when you make a mistake, indicating it by an orange or a red line. An
orange line means that you can run the program (but Matlab is unhappy
because of your bad coding practice) and the red line means that the
program cannot be run because of an error in that line. I will try and
explore common sources of error in Matlab in a later section.
You also necessarily have to make sure that you have saved your code in
the same directory as what Matlab is looking in when running the code in
the command window. I would recommend creating a Matlab folder in a
recognizable region of your hard drive and saving all .m (read as dot M
files) files there. When obtaining codes from other people, you could just
save it in this directory and run the file in the command window. We will
explore running .m files in the command window in a later example.
If you have a very clear code in your mind, you can actually type it all out
using notepad, in your email portal or even write it out on a piece of
paper. The only reason you actually need Matlab is to see how it all works
and to get your data.
4.
When running programs in the command window you can change the
variable name and it will just replace solution. For instance, [A] =
exmp_4(inp1,inp2) will give you the same result, but your answer will
be saved under the variable A.
Alternatively, you can just type exmp_4(inp1,inp2) for Matlab to spit out
the answer, given that you add the following line in your .m file:
disp(solution). Now, displaying the solution has become a function of
your code, and you dont have to call for the answer. Try to accustom
yourself with these techniques, because you will be using them for every
code you write. See Exercise 1.
5.
Presets
It is good coding practice, and also a good way to avoid orange lines, to
preset values for the variables you are planning to use. Matlab doesnt like
it (but at times will perform the program without complaining) when you
show it variables that it has never seen before. You have to say what the
initial value of the variable is. If it is an array, it is good practice to set up
an array of zeros of the required dimension.
6.
Commenting
Arrays
You will have to use arrays extensively in your projects and it would be
helpful if you were familiar with the different commands to manipulate
arrays. There is a comprehensive list of tricks in the following website:
http://blinkdagger.com/matlab/matlab-tips-and-tricks-onmanipulating-1-d-arrays-vectors/
I would strongly advice you to play around with them before attempting
to work on the projects.
Just to make this article complete, I have included a few basic array
manipulation techniques here.3
In addition to doing operations on single numbers, Matlab allows us to
perform operations on arrays. There are several ways to create an array, I
have listed examples in the bullet points:
3
Colon notation,
o array = 1:5, creates an array with elements from 1 to 5
using intervals of 1.
o array = 1:2:10, creates an array with elements from 1 to
20, using intervals of 2.
T*2
T/5,
T+20,
T/10+5
x.*y
x./y
x.^y
And now try to perform any one of those functions without the period. It
doesnt work because without the period, Matlab tries to perform a matrix
operation. The dimensions of x and y are inappropriate for such a
function.
A row vector can be turned into a column vector using the transpose (')
operator. Using the definition of t above, note what happens for the
command t' and t''.
We can also extract and modify elements of a list:
See Exercise 5.
8.
for loops
I will use the term iteration to refer to the loop number. First iteration will refer to the first
repetition.
5
Note carefully the position of the variable, and the position of the value assigned to that variable.
if constructs
The if construct is a simple, yet very useful function in coding. Lets look
at another problem.
Problem: Identify if a number is below 25 or between 25 and 75 or
above 75.
Solution:
function exmp_7(inp)
if inp < 25
disp('less than 25')
elseif 25 <= inp && inp <= 75
disp('between 25 and 75')
else
disp('above 75')
end
Although this could be an insultingly simple example, there are a few
important points to note. The elseif within the if construct will enable
you to add another condition, in case the first one isnt satisfied. The
else statement, gives the construct the option of performing the actions
that follow else, in the event that all the previous conditions werent
satisfied.
Now, note that Matlab does not accept statements like 25<inp<75. You
need to specifically mention that inp must fall between exactly these
two intervals using the && symbols. You have to use the symbol twice
because you are specifying a condition. Note that you will also have to use
== if you want to say that something is equal to something in your
condition. You can only use = when you want to store the value on the
right hand side (RHS) into the variable on the left hand side (LHS).
In one of the exercises you are required to make an if statement work
inside a for loop. Think through your process carefully before proceeding
with the coding for that.
I would strongly recommend you to take a look at the help section for if
to make yourself accustomed to the various less than and greater signs
that you can use to obtain your desired if statements.
See Exercises 2 and 3.
10.
Switch Case
With the following example, I will illustrate how the switch case method
can be used as an alternative to a series of if elseif statements. Lets say
we have a similar problem as before.
Problem: We are told that we will be given an input, which can
either be 1, 2, 3 or something else. We need to make a program
that will tell us which is which.
Solution:
function exmp_10(inp)
switch inp
case 1
disp('one')
case 2
disp('two')
case 3
disp('three')
otherwise
disp('others')
end
end
Notice, how you could have also tackled the problem using a series of if
elseif statements too, but the switch case function may prove to be
easier and cleaner. You might want to think of the switch function as a
train-track-directing switch. In the line switch inp you tell Matlab that
you are looking for the variable inp. In the following statements, you
give a list of cases detailing where the train should be directed if one of
the conditions are met. You may want to use this method to solve the
final exercise problem.
11.
while loops
i = 1;
while array(1,i) < num
i = i+1;
array(1,i) = array(1,i-1)+1;
end
disp(array)
end
Although there is a much easier way to generate this array:
function exmp_8-2(num)
array = [1:1:num]
end
I have used the first solution for a few reasons. It demonstrates that you
need an artificial iteration number in a while loop, unlike the for loop.
Since you have to make your own iteration number, you also have to
manually make the number go up by one each time the program goes
through the loop. Note that, this isnt always necessary in a while loop,
and that I had to make use of this little trick just to make a coherent
array.
Also, I chose this example because you cant always expect to have such
nice increments. You might face a problem with varying increments, like a
Fibonacci sequence. In fact that is an exercise included in this article.
Since this isnt a fantastic example, I also had to commit a subtle crime of
creating an array indefinitely increasing in size (which triggers the orange
line in the editor window). But, I get away with this because I know that
this isnt exactly indefinite, and that I know the loop will stop when I have
counted enough numbers.
See Exercise 4.
11.
Strings
You can make Matlab recognize, store and recall text. This will come in
handy when you are analyzing long strings of text. For example, we could
count the number of times the word the is used in a storybook using
strings6. I think the following website does a great job of explaining how
to make use of strings.
http://en.wikibooks.org/wiki/MATLAB_Programming/Strings
You might be at one point required to make use of the Map data
structure. A Map is a type of fast key lookup data structure that offers a
flexible means of indexing its individual elements. Unlike most array data
structures in Matlab that only allow access to the elements by means of
integer indices, the indices for a Map can be nearly any scalar numeric
value or a character string (words).
6
Remember that strings is just a fancy way of saying, I have stored a word in Matlab.
Indices (or elements) of a Map are called keys. These keys, along with the
data values associated with them, are stored within the Map. Each entry
of a Map contains exactly one unique key and its corresponding value. 7
At this point you might want to look up what containers.Map does. You
will be able to use this to make a dictionary to reference a certain string
to another string.
Dont worry too much about this section as I plan to make another set of
more detailed notes if and when you are faced with such a project.
12. Debugging
No matter how careful you are with your codes, you are at some point
bound to have made some mistakes in them. This can be either in the
form of an error, in which case Matlab will not perform the task, or in the
form of nonsensical results. There are a few ways you can solve the
problem.
You can go back to the editor and scan for the mistake and try
running the program in your head a few times. This involves mentally
running through the loops.
From http://www.mathworks.com/help/techdoc/matlab_prog/brqqo5e-1.html
have tried to explore some common sources of Matlab errors that you
might want to check for first in the event that you are faced with this
problem once you have completed your coding.
Firstly, dont try to code up something that looks smart enough to work,
without completely understanding how it works. I have tried this before,
and trust me, thats not how you code, and you will have no idea if the
data you are producing is right or wrong.
Presetting
As you might have already noticed in my example on the previous
page, it is good practice to preset your variables. It isnt good to
scare Matlab by suddenly introducing new variables in the middle of
the code.
For example, lets say you suddenly realized that you want to
include a variable X, an array, who will change with each iteration
of a for loop. Typing in X(1,i) = i*2 inside a for loop, for
example, will work. However, you need to tell matlab how big X is
first. I usually include presets immediately after the first line of my
code. In this case, if you are doing a hundred iterations of the for
loop, you should preset X to be, X = zeros(1,100). This isnt
always a fatal error, but you will get orange lines in the editor page.
Brackets
When, inserting complicated equations, Matlab might not be the
most helpful thing in the world. If you have had experience
Memory
Try to keep your programs as simple as possible. The more
complicated they are, the longer Matlab will take to process the
data. Get rid of redundant lines, and look for the simplest methods.
Matlabs command window will appear busy (on the bottom left)
when it is running the code. If a project that we assign you is going
to take a long time to run, we will let you know in advance.
Although Matlab is a very powerful tool, you need to remember that
it has a limited amount of memory. It is foolish to keep record of
redundant data. Always begin with the end in mind and remember
what final data you are interested in. Try to make Matlab forget
as much useless data as possible and only keep the essence of your
experiments. This will speed up processing time significantly and
help you write succinct codes.
Be on the lookout for lengthy periods of busyness. This usually
means that you have gone about the problem in a long-winded way
and Matlab isnt going to give you the solution anytime this week.
14.
Elegance
This isnt a programming course but a course on data analysis. You have
to remember that Matlab is only one amongst the many skills we teach
you here, and this course isnt about mastering Matlab.
So we dont care how you obtain your findings as long as you present it
in such a way that you demonstrate knowledge of the underlying
concepts. There are very many solutions to each problem you will be
assigned and there is no one right answer.
With that said, there are of course only a few elegant solutions. And I,
personally, am a big fan of elegant coding. I mention this here because
Exercises8:
1. Gas9
An equation of state for a non-ideal, which is commonly used, is the
van der Waals equation for 1 mole of gas:
P = (R*T)/(V-b) - a/(V^2)
where,
P = Pressure in Atmospheres
R = 0.0821 Atm*Liters/Mol*Kelvin
T = Temperature in Kelvin
V = Volume (in Liters)
The a and b values are10:
Ideal Gas: a = 0, b = 0 (so it reduces to ideal gas equation)
Nitrogen: a = 1.408 b = 0.0386
Oxygen: a = 1.378 b = 0.0318
For T=300 K and V=10L, calculate the pressure for nitrogen and
oxygen and compare the results with ideal gas.
Plot the pressure for oxygen & nitrogen for a range of volumes
from 0.1L to 10L (in steps of 0.05L) and compare to ideal gas
(To get you guys warmed up, below is the solution to the first
problem.)
Solution:
%Part 1
function [P] = ex_1_1(T,V)
a = [0 1.408 1.378]; %ideal gas, Nitrogen, Oxygen
b = [0 0.0386 0.0318];
P = (0.0821*T)./(V-b) - a/(V^2);
end
%Part 2
function ex_1_2(T)
i = 0;
a = [0 1.408 1.378];
b = [0 0.0386 0.0318];
array = zeros(3,199); %preset
for V = 0.1:0.05:10
i = i+1; %artificial counter
8
9
http://physics.gac.edu/~huber/matlab/mtlabpr1.htm
10
http://en.wikipedia.org/wiki/Van_der_Waals_constants_%28data_page%29
P = (0.0821*T)./(V-b) - a/(V^2);
array(:,i) = P;
end
x = 1:199;
plot (x,array(1,:),'k',x,array(2,:),'y',x,array(3,:),'b')
%see help plot
end
2. Simple coin toss
Find the percentage of heads occurring in a fair coin thrown
50, 100, 1000 and a million number of times respectively.
3. For and if
Generate an array of 10 random numbers between 1 and 100.
Then find out how many of the elements are between 1 and 25,
how many between 25 and 75 and how many between 75 and 100.
4. The Fibonacci Finder
Create a program that will distinguish a Fibonacci number from a
non-Fibonacci number. Hint: This is a review of while loops and if
constructs.
5. Discover Pi
Imagine the first quadrant of a circle in a Cartesian vector space.
Pick a few random points within this space and calculate the ratio
of the points that lay within the circle to those that are outside the
circle. Using this, determine the area of the circle, and calculate pi.
Increase the number of points within the space and see how it
affects your value of pi. You should get a fairly accurate value after
picking about a billion points. (The method is known as the Monte
Carlo Simulation)
6. Fold Mountains
(a)
11
Overlap depth of 1 would mean, the two 100s at the ends overlap, and overlap depth of 100 would
mean the two arrays overlap entirely.
100
100
100
1
1
100