Skip to content

Instantly share code, notes, and snippets.

@rscircus
Created July 21, 2022 10:58
Show Gist options
  • Save rscircus/d53f47b3bc76b11c7527e5a972490427 to your computer and use it in GitHub Desktop.
Save rscircus/d53f47b3bc76b11c7527e5a972490427 to your computer and use it in GitHub Desktop.
OCTAVE/MATLAB refresher while preparing for Interviews
format compact
%
% OOP
%
% INFO
% Must be created in own file with class name equal to filename -> shape
a1 = Shape(10,20);
disp(a1)
Shape.setGetNumShapes()
a1.getArea
a2 = Shape(5,10)
a1 > a2
a2 > a1
a3 = Trapezoid(10,4,6);
disp(a3)
a3.getArea
%
% FUNCTIONS
%
% INFO
% Matlab: Have to come at the end of a file (wtf...)
% Octave: The other way around...
function vol = cylinderVol(radius, height)
vol = pi * radius^2 * height
end
% Octave, as I'm using it
cylinderVol(20,30)
% locals / scope bound vars respect their scope
function changeVal()
changeMe = 10
class(changeMe)
end
changeMe = 5
changeVal()
disp(changeMe)
% argumentless
function randNum = getRandomNum
randNum = randi([1,100])
end
getRandomNum
% multiple return vals
function [coneVol, cylinVol] = getVols(radius, height)
cylinVol = cylinderVol(radius, height)
coneVol = 1/3 * cylinVol
end
[coneV, cylVol] = getVols(10, 20)
% mutliple arguments
function sum = getSum(varargin)
sum = 0;
for k = 1:length(varargin)
sum += varargin{k}(1); % matlab maybe can't += at least to Derek Banas Video Tutorial I'm watching
end
end
theSum = getSum(1,2,3,4)
% variable number of outputs
function [varargout] = getNumbers(howMany)
for k = 1:howMany
varargout{1}(k) = k;
end
end
listOfNums = getNumbers(10)
% anonymous functions (oneline functions)
cubeVol = @ (l, w, h) l * w *h;
cV = cubeVol(2,2,2)
% pass a function to a function
function result = doMath(func, op)
result = func(op)
end
mult3 = @ (x) x*3;
sol = doMath(mult3, 4)
% return a function from a functions
function func = doMath2(op)
func = @(x) x * op
end
mult4 = doMath2(4);
sol2 = mult4(5)
% recursive functions
% eval executes code which is saved as string
toExecute = sprintf("total = %d + %d", 5, 4)
eval(toExecute) % o_O
function val = factorial(num)
% TODO edge cases...
% base case
if num == 1
val =1;
else
val = num * factorial(num - 1);
endif
end
factorial(4)
%
% TABLES - not yet implemented in Octave 7.1
%
name = {'Jim'; 'Pam'; 'Dwight'}
age = [28; 27; 31];
salary = [35000, 26000, 75000];
id = {'1', '2', '3'};
employees = table(name, age, salary, ...
'RowName', id)
%
% STRUCTURES
%
dougSmith = struct('name', 'Dough Smith', ...
'age', 34, 'purchases', [12 23])
disp(dougSmith.age)
dougSmith.wife = 'Patty Smith' % can be extended dynamically
dougSmith = rmfield(dougSmith, 'wife') % remove field
isfield(dougSmith, 'wife')
fieldnames(dougSmith)
customers(1) = dougSmith;
sallySmith = struct('name', 'Sally Smith', ...
'age', 34, 'purchases', [12 23])
customers(2) = sallySmith;
disp(customers(2).name) %
%
% STRINGS
%
% basically works like an array
strArray = strsplit("I am a string")
disp('Class: ')
class(strArray)
strArray(1)
%
% Cellery - or cell arrays
%
how to store values of different types?
like a class, record or struct does?
cA1 = {'Dough Smith', 34, [25 8 1]}
cA2 = cell(5)
cA3 = {'Doug' 'Patty'} % character matrix
nameMat = char(cA3) % cell arrays into char matrices
cA4 = cellstr(nameMat) % char matrix into cell arrays
cA1{1} %get index
cA1{3}(2) % get element at index (works because there is a row vector)
cA1{4} = 'Patty Smith'
disp('Length:')
length(cA1)
cA1(4) = [] % delete?
for i = 1:length(cA1)
disp(cA1{i})
end
%
% MATRICES ENHANCED
%
% ; = don't display
m3 = [2 3 4; 4 6 8; 8 12 16; 16 24 32];
m4 = [1:3; 4:6];
m5 = [2:4; 5:7];
m6 = [1 2 3;
4 5 6]
m7 = [1 1 1 1;
2 2 2 2;
3 3 3 3]
% dot productish multiplication
m8 = m6 * m7
gT3M = m4 > 3
%sum(gT3M, 'all') %
% logical array / boolean array should be output_precision
isequal(m4, m4)
isequal(m4, m5)
find( m3 > 24 )
prod(m3) % multiply column values
cumsum(m3) % cummulative sum - ascending is default
cumprod(m3)
fliplr(m3) %columns
flipud(m3) %rows
rot90(m3)
rot90(m3, 2) % 180 degrees :-D
reshape(m3, 2, 6) % 2 by 6
m4 + m5 % add element wise
m4 .* m5 % multiply element wise
sqrt(m3)
m3 = m3 * 2
sqrt(m3)
sum(m3)
LOOPS
= 1
hile i < 20
if(mod(i,2) == 0)
disp(i)
i = i + 1;
continue % go back to while loop
end
%disp("else: ")
%disp(i)
i = i + 1;
if i >= 10
break % jump out of while loop
end
nd
FOR LOOPS
4 = [ 2 3 4; 4 6 8] % 2 row matrix
how to loop over it?
or row = 1:2
for col = 1:3
disp(m4(row, col))
end
nd
and a vector?
Vect = [ 6 7 8 ]
or i:length(IVect)
disp(IVect(i))
nd
for i = [ 2 3 4] % loop over 'vector'
disp(i)
end
for i = 10:-1:1 %backwards w/ start:step:end
disp(i)
end
for i = 1:10 % loops over 10 values from 1 to 10 inclusive
disp(i)
end
matrices
m1 = [ 2 3 4; 4 5 6]
mNRV = length(m1) % number of values in row
mNV = numel(m1) % number of all values
mS = size(m1) %dimensions
[nRows, nCols] = size(m1) %tuple save
% random stuff :)
m2 = randi([10, 20], 3) % values between 10-20 and 2x2
m2(1,2) = 22 % changes values
m2(1,:) = 25 % change all row values at row 1
m2(:,1) = 36 % change all col values at col 1
mR1Last = m2(end, 1)
MR2Last = m2(2, end)
m2(:,2) = []; % this clears colum 2
m2
vectors
% row or column vectors
% row vectors:
vt1 = [ 5 3 2 1 ]
vL = length(vt1)
vt1 = sort(vt1) %asc
vt1 = sort(vt1, 'descend')
vt2 = 5:10 % stepsize=1 (default)
vt3 = 2:2:10 % stepsize=2
vt4 = [vt1 vt2] % concat
% index starts at 1 omg
vt4(1)
vtEnd = vt4(end)
vt4(1) = 12 % overwrite
vt4
vt4(15) = 33 % gabs are filled with default vals
vt4(1:3) % range
vt4([ 2 4 6 ]) % specific indices
% column vectors
vt5 = [2;3;4]
vt6 = [1 2 3] %row
multiplication
1 2 3
2
3
4
results in matrix!
vtMult = vt5 * vt6
% dot product
vt7 = [4 5 6]
% (1*4) + (5*2) + (3*6) = 32
vtDot = vt6 * vt7' % transpose!
vtDotP2 = dot(vt6, vt7)
% cross product
vtCross = cross(vt6, vt7)
% create linearly spaced vector
vt8 = linspace(1,20,4) % 4 elements in space 1..20
vt9 = logspace(1,3,3)
if, else, elseif, switch, case
ge = 12
witch age
case 5
disp('You go to kg')
case num2cell(6:13) % this is incluse! and I found it out by experiment. :)
disp('You go to middle school')
case {14,15,16,17,18}
disp('High School')
otherwise
disp('Stay at home')
end
f age <=5
disp('You go to Kindergarden')
lseif age >5 && age <= 12
disp('You go to elem. school')
lse
disp('You are lost, because you are growing up')
nd
INFO: To get help type the following into the command window
doc
help
OPERATIONS AND OPERATORS
INFO
default precision is 15 decimal places
interesting operators
abs, floor, ceil, round, exp, log, log10, log2, sqrt, deg2rad, and so on...
printf('5^4 = ', 5^4)
printf('5 %% 4 = ', mod(5,4)) %escaping is %
everything is stored into 'ans' by efault
andi([10,20])
ns
I/O second part
sprintf('5 + 4 = %d\n', 5 + 4)
formats to string
DATA TYPES
primitive types
nt 8, 16, 32, char logical double single uint8...
% chars and ints
v4 = double('A')
v5 = char(64)
% everything is double by default!
v2 = 8
class(v2)
v3 = int8(v2)
class(v3)
% ranges for types
intmin('int8')
intmax('int8')
% multiline expression
v1 = 1 + 2 + 3 ...
+4
dynamic typing
c1 = 'A'
class(c1)
s1 = 'A string'
class(s1)
s2 = "A string"
class(s2) %string?
vInput = input("Enter a vector: ");
disp(vInput)
name = input('What''s your name?', 's')
if ~isempty(name)
fprintf("Hello %s\n", name)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment