# The_MATLAB_Language

## The Interface

• Script: code

• Live Script: text with code

• file names extension .m for script, .mlx for live script

>> isvarname(variable) %chekc if variable name is valid
>> exist(variable) %see if name exist already
>> clc %clear command
>> who %shows the names of defined variables
>> whos %shows the names of defined variables with more detail>> clear %delete variables from the workspace
>> clearvars var1 %delete the var1 from the workspace
>> clear var1 var2 var3 %delete the list from workspace
>> save datafile.mat %save file to datafile.mat
>> load datafile.mat %save file to datafile.mat
>> save justk k %save k variable to justk.mat
>> type [script_name_without_exttension] %see code
>> [script_name] %run code as a program


## Basic Syntax

• Line Break with ... after the line (like Python's \)

• adding semi-column can suppress the output, and typing variable name can see suppressed output.

• += is not recognized by Python

• a line var1 = 5;

## Types

• single: float

• double: high precision (default)

• int: signed and unsigned (int8, uint16)

• char: characters or strings

• logical: true and false

## Calculation Functions

sin(x) % sine with rad
sind(x) % sine in degree
log()
log10()
nthroot(base, pow)
min(A, [], dim)
max(A, [], nanflag)
rand() %random float range (0,1)
randi(imax) % random float range (1, imax)
randi([imin, imax], row, col) $random float range (imin, imax) round() % round to int fft() % discrete Fourier transform vpa() % show as decimal inv() % inverse of matrics transpose() % transpose of matrics eye(n) % identity matrics  ## Built-in Constants pi i %imaginary number j  ## Misc Functions class(x) %output the type of x help x %output the manual of x built-in function disp(x) %display x for the user help elfun % to show documentation in text doc [function] % to show documentation in web >>format long %15 decimal places (by default 4 decimal) >>format short %4 decimal places (by default 4 decimal) >>format shortEng %short with scientific notation (engineering) >>format longEng %long with scientific notation (engineering)  ## Arrays (index starts with 1, not 0) x=[7 9]; x=[7,9] %This is a row x=[7;9] %This is a column. x =[1 2 3 4 5] %This is also a column x=[1:4]; x=1:4 %output [1,2,3,4] (order matters) x=[1:0.5:5] %output 1~5 with 0.5 spacing x=linspace(first,last,number_of_elements) %same as above, default is 100 x=x' %transpose x=rand(5) %5X5 matrix of random number x=rand(n_row,_n_col) x=ones(n_row, n_col) x=zeros(n_row, n_col) x=size(x) %outpt the size of matrix x(row_col) %extract specific number in matrix x(end,3) %extract the end row, col=3 x(:,3) %extract all elements in row, col=3 x+1 %array element addition x/1 %array element division x+x %array element addition when size of the array is the same x+x' %array cross addition when size of the array is inverse x*y %matrix multiplication (multipliable) x.*y %element multiplication (same size) x.^2 %elementwise exponential dot(mat1,mat2) % dot product cross(mat1, mat2) % cross product [xrow,xcol] = size(x) [xMax,idx] = max(x) [~,ivMax] = max(v2) %ignore first output x(isnan(x))=0; %replace all NaN with 0  ## Matrix functions size(vec) % return(n_row, n_col) length(mat) % returns n_row or n_col, whichever is larger. numel(mat) %number of element x(end) % returns the right down corner of matrix reshape(x) % reshape into repmat(x, row, col) % copy paste matrics a few times fliplr(x) % flip left and right flipup(x) % flip up and down rot90(x) % rotate counterclockwise rot90(x, -1) % rotate clockwise  ## Plotting Line Specification figure(1) %finds a figure in which the Number property is equal to n, and makes it the current figure. or create one if it does not exist. You can put multiple plot in a figure. figure() %create a new figure without number plot(x, y) %plot y against x plot(x, y, str) %where str can be "r"(color), "--"(line style), "*"(dot style), ":."(filled circle) hold on %continue plotting in one graph hold off plot(v1, "LineWidth", 3, "DisplayName", "xxx", , 'MarkerSize', 6) %adding argument this way histogram(); bar() title("Plot Title", "fontweight", "bold", "fontsize", 24, "color", "green") xlabel("label"); ylabel("label", "frontweight", "bold") legend("x", "y", "z") legend({"y", "dy/dt"}, "Location", "northwest") % put legend left top xlim([xmin xmax]), ylim([ymin ymax]), zlim() loglog(x, y) %logl-log plot subplot(n_row, n_col, index); plot(data) % be careful that subplot will fill if you don't close it  ## Tables data.VariableName$extract table column
elements = sortrows(elements,'Mass') % you can click table to sort and update code


## Logic

& and %and
| or %or
if...elseif...else...end
for c=1:3...end
pause(0.2) %sleep 0.2 second
~= %inequal
~ %not

if
elseif
end

switch scalar/char vector/{"foo", "bar"}(for alias)/"foo"/
case xxx
action
otherwise
action
end

for iterator = range
action...
continue
end

for i = 1:length(list)

while
end


## Commenting

%{ this is A HUGE PARAGRAPH %}
%% SECTION I


## Input

variable = input(What is your variable: ,"s") % for input as a strong


## Output

fprintf('string', value1, value2,...) % if value is a vector, then print will repeat for each value until there is no place holder left

%d = integer
%f = float
%c = single character
%s = string

place_holder = %
convertion_character = letter
between = field width



## Dictionary

dic = {}
dic{1,key} = value;


## Functions

f = @(a,b,c) a+b+c % create functions
f(1,2,3)

syms a b c % create symbolic variables
equation = a+b+c
a = solve(equation, a, 'Real', true)
vpa() % for numerical output

% function_name should equal file name
% function will automatically loaded in the folder
% function need all required input, but not all required output
% to create function, create a new file
% all functions in matlab cannot have repeated name
function [output_name] = function_name(input_name)
% description of function as a commentary
body
end

% if there is only one output needed, function will give you the first output
[~, value] = function(x, y) % ignore output

% getting help of sub_function
% you cannot access sub_function
% the first function in the file is primary function, others are sub functions
help primary_function>sub_function

% anonymous function (generally for live editor)
fn_name = @(inputs) body_of_function;
fn_name = @() body_of_function;

fn_name(inputs)
fn_name()

% function function
% function that takes in a function as input
function(@function) % how you pass function inside function



X = linspace(-2*pi, 2*pi)
Y = linspace(-2*pi, 2*pi)
[x, y] = meshgrid(X, Y)
z = sin(x) + cos(y)
mesh(x, y, z) % mesh plot: with lines
surf(x, y, z) % surface plot: with surface
contour(x, y, z) % slicing with all z value
contour(z, [...]) % slicing with some z value
contour(x, y, z, #num) % slicing with #num many z value

[X, Y]
Z = some function that takes X and Y
DX = some function that takes X, Y, Z
DY = some function that takes X, Y, Z
quiver(X, Y, DX, DY) % quiver plot show vector that depend on location


## Curve Fitting

f = @(x) some polinomial
coeffs = [...] % coefficient of polinomial from high to low
roots(coeffs) % calculate root
poly(roots) % create coefficient by root
polyfit(X, Y, n) % make coefficient vector for n degree polinomial
polyval(coeff, X) % evalueate for all x in X
plot(x, polyval(coeff, x)) % find out value in between datapoint % interpolation (inside of bound of dataset)
% extrapolation (outside of bound of dataset)
y_result = interp1(x_data, y_data, x_result) % linear interpolation (just a linear line between two points)
y_result = interp1(x_data, y_data, x_result, "spline") % spline (automatically smooth by matlab)
y_result = spline(x_data, y_data, x_result) % another way to do spline


## Symbolic Tool Box

https://www.mathworks.com/help/symbolic/calculus.html

### Integration

trapz(X, f) % Trapezoid Rule summing up function f by points X
quad(f, from, to) % simpson's rule (tolerance 1^-3) for integration (take input in function)
polyint(coeffs) % return coeffs of a polynomial's intergration
syms x, y, z % symbolic tool box
f = function
int(f) % in symbolic, return the analytic integral function (take input in symbolic)
int(f, from, to) % in symbolic, return the definite integral (take input in symbolic)



### Differentiation

% polinomial
polyder(coeffs) % return coeffs of a polynomial's differentiation

% finding analytic derivatives indirrectly
syms x, y, z, h
f = @(x, y, z) function % make symbolic function
limit((f(x+h)-f(x))/h, h, 0) % finding analytic derivatives

% finding analytic derivatives dirrectly
syms x, y, z % symbolic tool box
f = function
diff(f) % finding analytic derivatives


### Ordinary Differential Equations

% ordinary = no partial derivatives, only 1 changing variable
f(\frac{dy}{dt}, y, t) = 0 % ordinary differential equation
\frac{dy}{dt} = 5y + 5 % ordinary differential equation

time_span = [from, to] %
y0 = [y, dy/dt]
[t, y] = ode45(@dydtfunction, time_span, y0) % a graph that find y and dy/dt. y is a matrics [variable, derivatives of variable]
plot(t, y(:,1)) % plotting value (in this case y)
plot(t, y(:,2)) % plotting value's derivatives (in this case dy/dt)
function dydt = dydtfunction(t, y)
dydt = function
end


#### Example

dh_dt = @(t, h) -sqrt(2*g*h)*(d/D)^2

t = [0, 500] % integrate against
h0 = [8, dh_dt(0, 8)] % correspinding to t0

[t, H] = ode45(dh_dt, t, h0)
plot(t, H(:,1), "DisplayName", "height") % plotting value (in this case H)
plot(t, H(:,2), "DisplayName", "dh/dt") % plotting value's derivatives (in this case dH/dt)



### Second Order Differential

% change second order differential equation into first order ordinary differential equations
y'' + y' log(y) - y^2 = c
x(1) = y
x(2) = y'
d(x(1))/dt = x(2)
d(x(2))/dt = y'' = c - y' log(y) + y^2 % = c - x(2) log(x(1)) + x(1)^2 % solving for y''

x = [y, dy/dt, dy'/dt at time 1
y, dy/dt, dy'/dt at time 2
y, dy/dt, dy'/dt at time 3 ] % in order of x(1) x(2) x(3)...



TODO: https://canvas.cmu.edu/courses/19032/assignments

Table of Content