Skip to content

Instantly share code, notes, and snippets.

@sg-s
Last active February 10, 2021 21:03
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 sg-s/8863744f1202a3f1f5790e837af37a8e to your computer and use it in GitHub Desktop.
Save sg-s/8863744f1202a3f1f5790e837af37a8e to your computer and use it in GitHub Desktop.
Extremely basic MATLAB crash course

How to make a vector

a = [1; 2; 3]
a = [1, 2, 3] % avoid
a = zeros(10,1)
a = ones(10,1)
a = NaN(10,1)
a = linspace(0,1,10)
a = logspace(-1,1,10)

change an element in a vector

% change one element
a(2) = 2;

% change many elements
a(2:4) = [2;3;4];

broadcast a value

a(:) = 1;

% note that this is different from
a = 1;

make two vectors of the same size

a = linspace(0,1,100);
b = 0*a;
c = NaN*a;   % preferred 

iterate over a loop and do an operation element-wise

This is the standard way you would do this

a = linspace(0,1,100)
b = NaN*a;

for i = 1:length(a)
  b(i) = a(i)^2;
end

This is bad (because the size of the vector changes every iteration)

a = linspace(0,1,100)
b = [];

for i = 1:length(a)
  b(i) = a(i)^2;
end

Looping backwards is OK, and automatically pre-allocates a vector

a = linspace(0,1,100)
b = [];

for i = 1ength(a):-1:1
  b(i) = a(i)^2;
end

Vectorized operations

Note that not all operations can be vectorized; you may have to use for loops

a = linspace(0,1,100);
b = a.^2; % the . is important
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment