Skip to content

Instantly share code, notes, and snippets.

@DoubleMalt
Last active August 29, 2015 13:57
Show Gist options
  • Save DoubleMalt/9590174 to your computer and use it in GitHub Desktop.
Save DoubleMalt/9590174 to your computer and use it in GitHub Desktop.
%*************************************************************************%
%%------------A SHORT INTRODUCTION TO MATLAB VIA EXAMPLES----------------%%
%*************************************************************************%
%This short introduction to Matlab will take you through the essentials you
%will need for your problem sets. There will be times when you will need
%to look up stuff on your own. To that end, the INTERNET is useful, but
%also the command: help. Here's how you use it:
help sum
%Saving variables is easy; you just use =
var1 = 2;
%The use of the semicolon has the function of suppressing the result (or
%command). To "echo" the result, you just leave the semicolon out:
var2 = 3
%Check to see if the variables are equal with ==
var1 == var2
var1+1 == var2
%There are many mathematical built-in variables and functions that can be
%used, for example: pi, i, sin, exp. It's not smart to use these as your
%own variable names (even if it can be done).
%%-------------------------------VECTORS---------------------------------%%
%Everything in Matlab is done via MATRICES. Even the variable var1 above
%is stored as a 1x1 matrix. Let's look at how to work with a special class
%of matrices - 1xN or Nx1 matrices (aka VECTORS).
%Creating a vector:
a = [1 2 3 4 5] %row vector
b = [1; 2; 3; 4; 5] %column vector
%Note that b could have been defined this way:
beasy = a'
%Even easier:
aeasy = 1:5
c = 1:2:10 %create vector of odd numbers between 1 and 10
d = 8:-3:1 %for d = (8,5,2)
%If you want to know the length of the vector, use the function length:
length(a)
%You can dynamically add items to the vector as follows:
a = [8,a,6]
%Or even:
a(10) = 10
%Can you append vectors together (assuming the dimensions work)? Yes!
longvect = [a,c]
%To change a value...
a(1) = 0
%Or access one...
a(2)
%What if you just wanted even values of longvect?
longvect(2:2:end) %end just means the last index in the vector
%Some other shortcuts:
sort(longvect) %return longvect with values in ascending order
unique(longvect) %same as sort and remove duplicates
find(longvect>4) %return INDICES of longvect with values greater than 4
longvect(find(longvect>4)) %return values of longvect greater than 4
max(longvect)
min(longvect)
abs([-3,-2])
sum(1:100)
prod([3 10 4])
x = zeros(5,1) %preallocate 5x1 matrix with just zeros
x = ones(1,6) %preallocate 1x6 matrix with just ones
x = rand(5,1) %5x1 matrix with random values in [0,1]
clear %delete all variables
%%-------------------------------MATRICES--------------------------------%%
%Now let's switch to matrices. If you've understood vectors, then you will
%get the hang of matrices quickly. Let's create a 2x3 matrix:
A = [1 2 3; 4 5 6]
%This could have been created by concatenating column vectors:
A = [[1;4] [2;5] [3;6]]
%Dynamically add elements to A:
A(5,1) = 500
%Accessing an element works similarly to what we did for vectors:
A(2,1)
%Access the first row of A:
A(1,:) %the shorthand : simply means the entire row
%Access the second column of A:
A(:,2)
%Instead of length, we use size for matrices (size can be used on vectors,
%too!)
[M,N] = size(A)
%Shortcuts:
zeros(2,5) %create 2x5 matrix with zeros
ones(2,2) %create 2x2 matrix with ones
rand(3,1) %column vector of random values in [0,1]
eye(5) %5x5 identity matrix
%%-----------------------OPERATIONS ON MATRICES--------------------------%%
%Now let's look at operations that can be performed on matrices (and
%vectors). The default arithmetic are those as defined using matrices.
%This means that you need to make sure that your dimensions are compatible!
%Adding matrices
A + ones(M,N) %matrix plus matrix (same dimensions)
A + 1 %matrix plus scalar yields the same result (in this case)
%Multiplying matrices
A * [1 1 1]' %note the ' .... dimensions must match!
A * [1 2; 3 4; 5 6]
%Division
A/2 %Divide each component by 2
2\A %Does the same thing
%For matrices (with compatible dimensions), the following shortcuts are
%also useful:
% X\A ... X^(-1)*A
% A\X ... A^(-1)*X
% X/A ... X*A^(-1)
% A/X ... A*X^(-1)
%These operations are even defined on non-invertible matrices!
%Inverting a matrix
B = eye(5); B(1,1)=3;
B^(-1) %Invert matrix
B\eye(5) %This is the same as B^(-1)*I (I...Identity matrix)
%Powers of matrices
B^3 % B*B*B
%It's also possible to perform multiplication and division on each
%component.
B = [1 2 3; 4 5 6]
C = [2 0 0; 2 2 2]
B.*C %B(i,j)*C(i,j) for all i,j
B./C
B.^C
clear;
%%----------------------LOGICAL OPERATORS--------------------------------%%
% ~ ... Not
% || ... Or
% && ... And
% < ... Less than
% <= ... Less than or equal to
% > ... Greater than
% >= ... Greater than or equal to
% == ... Equal to
% ~= ... Not equal to
x = [1 8 2 7 6 8 9 1];
x > 3 %Returns 0 for x<=3, 1 for x>3
x(x>3) %Returns elements that are greater than 3
find(x>3) %Returns indices of nonzero elements
%%---------------------------FUNCTIONS-----------------------------------%%
%First line: function [out1,out2]=function_name(input1,input2,input3).
%Or: function function_name(input1,input2) without an output value
%Or: function [out1] = function_name without input values
%Etc...
%A simple example:
function [ px ] = evalpoly(a,x)
%Evaluate a polynomial p with coefficients a at point x
%a(1) is the coefficient of the smallest power, a(length(a)) is the leading
%cofficient
px = a * (x.^[0:length(a)-1]);
end
%%------------------LOOPS AND OTHER STUFF--------------------------------%%
% if, elseif, else, end
a=3; b=2;
if a > b
disp('a>b')
elseif a == b
disp('a=b')
else
disp('a<b')
end
% while, end
a=2; b=10;
while(a<b)
a=a+1.1
end
clear;
%%-------------------------PLOTTING--------------------------------------%%
%To create a plot, you need to create a vector for the domain, and another
%(of equal length) for the range.
figure(1)
x = -6:.5:6;
y = exp(-x.^2);
plot(x,y)
figure(2) %finer grid
x = -6:.01:6;
y = exp(-x.^2);
plot(x,y)
%Adding multiple plots to the same figure with the hold on/hold off syntax:
z = x.^2/30;
plot(x,y,'b')
hold on %Tell Matlab to use same plot for next command
plot(x,z,'r')
hold off
%Adding legends, axis labels and titles:
legend('exp(-x^2)','x^2/30')
xlabel('Interval [-6,6]')
ylabel('Function values')
title('Plot with labels and legend')
%Also useful:
loglog(x,y) %the same thing as plot(log(x),log(y))
semilogx(x,y) %plot(log(x),y)
semilogy(x,y) %plot(x,log(y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment