MATLAB Intro for Project 1

Getting Acquainted with MATLAB

Starting MATLAB

You should first move to a new folder in your cs016 directory for saving all of your matlab files (e.g. cs016/someProject/). You can open MATLAB from the command line by then typing:

cslab1a /u/username/cs016/someProject % matlab

You should see three panels in the MATLAB window.

The Command Window gives you a prompt where you can execute MATLAB commands similar to the command prompt in Linux. The Command History shows you commands you have typed in the Command Window recently.

The Current Directory window displays the files which are in the current directory. You will create your sorting algorithms as MATLAB files, or "m -files" (files that end in .m). You can create new m files going to File -> New -> M-File. Doing so will open another window where you can start writing MATLAB code.

Your m-files will each contain one main function which will be "executable" from the Command Window and this main function should have the same name as the file, similar to Java functions.

For example, a file myFunction.m with three input variables and three output variables might look like:

function [output1 output2 output3] = myFunction(input1, input2, input3)
	% your code here
end

You can include additional helper functions elsewhere in the file.

Then myFunction.m can be used at the command window or in another file which is in the same directory by typing:

> a, b, c = myFunction(var1, var2, var3)

The Colon Operator

The colon operator is a really useful construct that allows you to create a list of numbers based on any pattern. Given integers j and k specifying starting and ending integers and (optionally) i specifying the how much to increment, the colon operator will create lists of numbers as follows:

j:k is the same as [j,j+1,...,k]
j:k is empty if j > k
j:i:k is the same as [j,j+i,j+2i, ...,k]
j:i:k is empty if i == 0, if i > 0 and j > k, or if i < 0 and j < k

Consider the following examples:

>> 5:1
ans =
Empty matrix: 1-by-0

>> 5:-1
ans =
Empty matrix: 1-by-0

>> 5:-1:1
ans =
5 4 3 2 1

>> 0:pi/2:2*pi
ans =
0 1.5708 3.1416 4.7124 6.2832

Notice that when i is not specified, it is 1 by default.

Conditional logic

MATLAB has conditional logic operators similar to those you are used to in Java. However, there are some key differences. One thing to note is that you do not use curly brackets ({ and }) in MATLAB to segment blocks of code. Instead, you will use the 'end' keyword to denote the end of a code block.

If/Else Statements

Conditional logic statements such as if, else if, else work in MATLAB.
You can use the following syntax:

if <condition1>
<code1>

elseif <condition2>
<code2>
end

For example, consider the following Java example translated into MATLAB:

int n = 5;
int b;

if (n % 3 == 0)
	b = 0;
else if (n % 3 == 1)
	b = 1;
else
	b = 2;

Which is equivalent to the following code in MATLAB:

if mod(n,3)==0
	b=0;
elseif mod(n,3)==1
	b=1;
else
	b=2;
end

For loops

For loops are even easier in MATLAB than they are in Java. You can iterate over a range first to last easily with the following syntax:

for i=first:last % note the use of the colon operator!
	<code>
end

Then i is accessible in the block of code with the current value from first to last.

Here's a simple example of a for loop in Java then translated into MATLAB:

for (int i = 1; i <= 5; i++) {
	System.out.println("Number " + i + "!");
}

Then in MATLAB:

for i = 1:5
	display(['Number ' int2str(j) '!']);
end

Variables/Arrays

Unlike Java, MATLAB is totally chill when it comes to declaring variables. You don't need to declare a variable in order to set it, though a variable must have a value in order to use it (or you will get an error.)

For example, the following code is completely valid:

i = 3;
i = 'hi mom';

The variable i will first be set to 3 and then the string 'hi mom'. Notice that the variable never had to be explicitly typed (it was never declared as an int or a string.) You can't do this in Java!
Arrays are also really easy to create in MATLAB. You can either create an array with explicitly by inserting or telling MATLAB what every element is or by 'allocating' an empty array of a given size.

% Explicity create an array of odd numbers up to 10:
a = [1, 3, 5, 7, 9];

% You can also explicitly create arrays with MATLAB's colon
operator:

% This creates an array b, with values [1,2,3,4,5,6,7,8,9,10]
b = 1:10;

% You can look up MATLAB's colon operator and get super fancy:
% Create [1,3,5,7,9]:
c = 1:2:9; % Iterate from 1 to 9 every _second_ element

% Declare an empty array of size 10:
d = zeros(1,10);

% Declare an empty array of size n:
e = zeros(1,n);

% You can index into existing arrays with the following syntax:

A = 1:10;
A(3); % gives the 3rd element, 3
A(4:7); % gives an array with the 4th through 7th elements
A(:); % gives the entire array, this is shorthand notation!

Graphing

We pretty much set you up with all the graphing code you need to, but here are the basics for graphing in MATLAB anyway.

You can easily plot an array A with:

plot(A);

Alternatively, you can plot a set of x, y coordinates if you have two arrays X and Y (containing the x and y coordinates respectively) by typing:

plot(X,Y);

For example, consider the following example which plots x coordinates from 1 to 10 with random y values:

plot(1:10, rand(1,10)); 
% (the rand function creates an array of random values)

You can annotate your plots with the title, xlabel and ylabel functions:

xlabel('The x-axis: values from 1 to 10');
ylabel('The y-axis: random values between 0 and 1');
title('Plotting values from 1 to 10 with random y values.');

Wrap Up

That all you should need to know about Matlab in order for you to do your first project, "runtime". This is certainly not everything there is to know about Matlab and if you want to expand your knowledge of or have questions about Matlab, consult Matlab's "Help" section. If that does not satisfy you, see a TA on hours, post to the Google Group, or email the TAs with your questions.

Last Second Aside:

You may want to change the keyboard settings for Matlab from Emacs to Windows, so here's how:

And now you should be able to use Windows hot keys.