Skip to content

Instantly share code, notes, and snippets.

@giuseb
Created May 26, 2015 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuseb/b2ecd26a42d50199a7e9 to your computer and use it in GitHub Desktop.
Save giuseb/b2ecd26a42d50199a7e9 to your computer and use it in GitHub Desktop.
% The command line starts with a prompt waiting for user input; typing
% something at the prompt and pressing Enter invokes the interpreter; if
% the string is valid, Matlab will process the input and act accordingly,
% otherwise an error is raised and the relative message is shown below the
% input string
%
% At the command line, when you type a number and press enter
% Matlab will respond with that number
123
%%
% but if you type something funky, Matlab will complain. Try for example to
% enter the command: 123+
%% Operators and expressions
% here are several basic arithmetic operators
4+5
7-9
6*6
8/3
2^8
%%
% pay attention to the order of precedence;
% what's the average between 3 and 5?
3+5 /2
(3+5)/2
%%
% another example of precedence issue: the square of a negative number is
% always positive:
-3^2
(-3)^2
%%
% Here's the order of precedence for a few operators; when in doubt, always
% use parentheses to enforce correct precedence!
%
% # |^ Exponentiation|
% # |* Multiplication|
% # |/ Right division|
% # |+ Addition|
% # |- Subtraction|
%% Command-line output format
% what you see in the CLI in response to a command may well differ from the
% internal representation of the values
10/3 % what does it look like?
format long
%%
10/3 % what does it look like now?
%%
format % by itself, reverts to the default
format compact % makes the output more... compact
%%
% look at the scientific number notation
923874392874*049350934
%%
% I can write a number in scientific notation
6.022e23
6.626e-34
%%
% Beware: digital numbers are approximate! Look at this simple example:
0.4^2
%%
% the following reveals an intrinsic limitation of digital computations
0.4^2 - 0.16 % the result should be zero, right?
%% Introducing the Editor
%
% instead of directly using the command line, we can write scripts
% and save them for later use! If not already available in your window
% layout, open the editor by invoking it at the command line:
edit
%%
% The code we type in the editor can be executed in different ways; for
% example, enter the name of the saved text file at the command line. There
% are also platform-dependent keyboard shortcuts.
%
% By default, Matlab displays in the command window all the results of all
% computations. This can be extremely inconvenient if you are handling
% large amounts of data. To prevent verbose output, terminate each line of
% code with a semicolon
%% Vectors and matrices
% Matlab easily supports vectors, i.e. lists of values
[3, 5, 7, 9]
[0, 0, 0]
[2, 1, 4, -3]
%%
% the following two are equivalent
[3, 4, 2, 0]
[3 4 2 0]
%%
% the semicolon has a different effect!
[5; 9; 0; 1]
%%
% we are not limited to integers; notice that the default format changes
% when you have decimal digits in a vector
[3, 7, -4, 1.1]
%%
% use the quote operator to transpose vectors
[3 5 7 9]'
[5; 9; 0; 1]'
%%
% the colon operator lets us quicly generate ordered series of numbers
1:6
2:3:15
42:-2:-11
3:.1:10
%%
% note the order of precedence: which one will transpose properly?
1:6'
(1:6)'
%%
% a 2-dimensional array is commonly defined a matrix
[1,2,3,4; 8,6,4,2; 0,0,0,1]
% ...which can also be written...
[1,2,3,4;
8,6,4,2;
0,0,0,1];
%% Operating on vectors
% look at the results of the following
1:10 + 2
[3, 4, 5] * 1.5
%%
% you can perform element-wise additions and subtractions on vectors and
% matrices, provided they have the same size
[3, 5, 7, 9] + [2, 1, 4, -3]
(1:4)' - [3; 5; 1; 0]
%%
% careful how you match your vectors
%
% [3, 5] + [2; -3]
%%
% element-wise multiplications and divisions use a different operator (for
% reasons that are beyond the scope of this tutorial)
[3, 5, 7, 9] .* [2, 1, 4, -3]
%% Variables
% the result of this operation (it could be the area of a triangle) is
% displayed on the command line and then quickly forgotten about
3*4/2
% if we need the result of an operation for later use, we must assign it to
% a variable
a = 3*4/2
% the above is not an equation, i.e. it is not an assertion on the
% equality of two expressions; rather the statement says: "create a
% variable in the current workspace named 'a', and place there the result
% of the operation on the right-hand side of the equal sign.
% a better way to compute the area of a triangle
b = 4;
h = 3;
a = b*h/2
% it may seem like a waste of typing, but it is always good programming
% form to separate as much as possible the data from the logic
%%
% More on arrays and matrices
ve = 10:10:40;
ma = [ve;
8,6,4,2;
0,0,0,1];
%%
% different ways to concatenate matrices; we are not assigning the results
% of these expressions to variables, because we only want to take a quick
% look at the outcome
[ma; ma]
[ma, ma]
[ma; 3:6]
[100, 1:34, ve, -1, 5:-2:-12]
%%
% always pay attention to the "orientation" of your vectors
a = [2, 4, 6, 8];
b = [1, 3, 5, 7];
[a, b]
[a; b]
[a; b]'
%%
% again, watch out for matrix dimensions!
% the following is OK:
k = [5 2 9];
m = [0 2];
[k m]
%%
% ...but the following would produce an error:
%
% [k; m]
%% Functions
% We have seen simple math operators, but what about things like square
% roots or trigonometric functions?
root = sqrt(9)
roots = sqrt([4, 9, 25])
%%
% The word |sqrt| is the name of a function, a chunk of code that performs
% computations and returns some results. In most cases, a function needs
% some information in order to work properly. In the above examples, the
% values in parens are the "argument" passed to the square root function.
%%
% Hundreds of functions are available in Matlab;
% see also <http://www.mathworks.com/help/matlab/functionlist.html>
data = [3,5,4,6,7,3,4];
sum(data)
mean(data)
%%
% Getting help on a function, to learn how it works:
%
% help sum
% doc sum
%
% Viewing the code and editing a function:
%
% edit mean
%
% Some low-level functions cannot be edited:
%
% edit sum
%%
% Here's a few very important matrix-building functions:
rows = 3;
cols = 4;
zeros(rows, cols)
ones(rows, cols)
%%
% uniformly distributed random numbers between 0 and 1. Note that several
% more functions are available for random number generation
rnd = rand(rows, cols)
%%
% the function |repmat| uses an input matrix to create "tiles" of data
a = [1,2; 3,4];
tiled = repmat(a, rows, cols)
%%
% A very common task is to find the size of a matrix
sides = size(rnd) % number of rows, number of columns
[nrows, ncols] = size(rnd)
%%
% for simple vectors, you can do:
a = [2, 4, 6];
length(a)
%% Extracting values from existing matrices
% One of the most common tasks in Matlab is to access subsets of data from
% previously defined matrices. This is done by "indicizing", i.e. placing
% in parentheses, after the variable name, one or more values indicating
% the position of the values to access.
data = [10,20,30,40,50,60,70];
data(3)
data(4:6)
data([1, 3, 5])
%%
% The keyword |end| indicates the *last* element in the array
data(end)
data(end-2)
data(end-2:end)
%%
% Note that trying to access an element that does not exist is forbidden
%
% data(12) % raises an error
%%
% With 2-D matrices, you need 2 indices
ma = rand(rows, cols);
ma(2,1) % returns the element on the 2nd row, 1st column
ma(1:2, 1:3) % returns the first two rows and the first 3 columns from ma
%%
% to access entire rows/columns, use the colon operator by itself
ma(3,:)
ma(:, 3:4)
ma(2:end, :)
%%
% indexing can also be accomplished by using logical values
true % returns what "looks like" a 1, but is really the boolean "true"
false % returns what "looks like" a 0, but is really the boolean "false"
data = [10,20,30,40,50,60,70];
idx = [false false true true true false]; % creates a logical vector
data(idx) % only the values at "true" positions are returned
idx = logical([1 0 0 0 0 0 1]); % numbers can be "cast" into logicals
data(idx) % this will work as well
%% Logical expressions and matrix indices
% Arrays of logical values are typically generated by evaluating logical
% expressions. First, a double equal sign is used to assess equality
% between vectors:
3 == 2+1 % returns true
0 == 1 % returns false
1:5 == [1 1 3 5 6] % returns [true false true false false]
%%
% Less than and greater than (with or without equal) than can also be used
1:5 > 2 % returns [false false true true true]
[2 4 6 8] <= [3 1 9 4] % returns [true false true false]
%%
% Using a logical expression as a matrix index
data = rand(1,10);
data(data < .3)
%%
% although the above code is compact and perfectly legal, it is often
% better to be less "smart" and more explicit
small_values = data < .3; % true values whenever the condition is met
data(small_values) % extracts the "small values" from data
%%
% Here's a practical example of using a logical array to exclude outliers
% from a dataset. Fake data are generated with the function |normrnd|,
% which produces normally distributed random numbers around a given mean
% and with a given standard deviation.
average = 50;
st_dev = 10;
data = normrnd(average,st_dev, 1, 100); % fake data set
small_outs = data < average - st_dev*2; % data below 2 stdevs from mean
big_outs = data > average + st_dev*2; % data above 2 stdevs from mean
all_outs = small_outs | big_outs; % logical "or" operation
ok_points = ~all_outs % the tilde negates the vector
data(ok_points) % returns all outliers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment