# Matrices ## Generate ### Manual matlab A = [1 2 3; 4 5 6] A = 1 2 3 4 5 6  ### Zero matlab A = zeros(3) % 3x3 B = zeros(3, 2) % 3x2  ### Ones matlab A = ones(3) % 3x3 B = ones(3, 2) % 3x2  ### Eye (zeros with ones in the diagonal) matlab A = eye(3) % 3x3 B = eye(3, 2) % 3x2  ### Magic matlab A = magic(3) % 3x3  ### Random values (from 0 to 1) matlab A = rand(3) .* 2 % 3x3 with values from 0 to 2 B = rand(3, 2) % 3x2  ### Normally distributed random values (σ = 1, µ = 0) matlab A = randn(3) .* 2 % 3x3 with σ = 2, µ = 0 B = randn(3, 2) % 3x2 C = randn(3, 2) + 3 % 3x2 with σ = 1, µ = 3  ## Modify ### Transpose matlab T = A'  ### Invert matlab B = inv(A)  ### Rotate matlab B = rot90(A)  ### Flip matlab B = flip(A) % flip rows (top to bottom) B = fliplr(A) % flip columns (left to right)  ### Multiply matlab C = A * B  ### Element wise multiplication matlab C = A .* B  ## Access ### As row vector matlab A(:)  ### Get rows matlab A(1, :) % row 1  ### Get columns matlab A(:, 1) % column 1  ### Get diagonal matlab diag(A) % main diagonal (top left to bottom right) diag(flip(A)) % other diagonal (bottom left to top right)  ## Linear equations matlab x = A \ b % solves Ax = b  ## Find indices matlab i = find(A); % find all nonzero elements i = find(A > 1); i = find(A < 1, 5); % get the first five elements  # Images ## Load image matlab img = imread('path_to_file')  ### Show image matlab imagesc(img)  ### Color map matlab colormap(gray()) % gray color map colormap(M) % where M 255x3 with values from 0 to 1  # Datatypes ## Struct matlab student.name = "TestStudent" % create student.age = 24 % add field student2 = struct('name', 'Student2', 'age', 23) % compact disp(student.name) % print name  ## CellArray Array containing different data types ### Create matlab ca = { 'chars', 9.81, 1 } % 1x3 cell array  ### Access elements matlab ca(1) % -> 'chars'  ### Get length matlab length(ca)  ## Table ### Properties matlab table.Properties table.Properties.VariableNames{1} % first column name  ### Access column by name matlab table.column_name % access column (as vector) with name "column_name"  ### Get sub-table matlab table(:, 2) % second column as table  ### Access values matlab table{1, 2} % row 1, column 2, note brackets! table{:, 2} % column 2  ## Strings ### Create matlab str = "Hello" fromChar = string(text)  ### Concatenate matlab str2 = str + " World!"  ## Character array ### Create matlab text = 'Hello' fromStr = char(str)  ### Concatenate matlab text2 = [text ' World!']  ### Access characters matlab c = text(1) % first character  ### Convert to number matlab str2num('2')  ## Output ### Create formatted string matlab sprintf('value: %f', float_val)  ### Print string matlab disp('Hello')  ### Print formatted string matlab % use \n for newline, the 1 is for printing to stdout fprintf(1, 'value: %d\n', 2)  # Save and load ## Workspace matlab save file_name save file_name a b c % only save a, b and c load file_name  ## Table matlab table = readtable('file_name') detectImportOptions('file_name') % return detected import options  ## Matrix matlab matrix = readmatrix('file_name') % like readtable but only values as matrix  ## File matlab file_handle = fopen('file_name', 'rw') % open as readable and writable fclose(file_handle)  # Polynomials ## Create polynomial from roots matlab p = poly([1 -2 3]);  ## Fit polynomial to points matlab % x and y: coordinate values, deg: degree of polynomial p = polyfit(x, y, deg);  ## Calculate values matlab % get y values for vector x and polynomial x y = polyval(p, x);  ## Multiply polynomials matlab p3 = conv(p1, p2);  ## Get roots matlab r = roots(p);  # Graphics ## Plots ### Plot matlab x = 1:10; y = x.^2; plot(y); % automatic x-axis plot(x, y); % custom x-axis  ### Stairs plot matlab stairs(x, y); % plot values as stairs  ### Discrete values matlab ffty = fft(y); % fast-fourier transform stem(x, abs(ffty)); % plot FFT  ### Logarithmic matlab loglog(x, y); % both axes are logarithmic  ### Semi-logarithmic matlab semilogx(x, y); % x-axes is logarithmic, y-axis is linear semilogy(x, y); % x-axes is linear, y-axis is logarithmic  ### Simple function plot matlab fplot(@sin); % default, from -5 to 5 fplot(@sin, [-pi pi]); % from -pi to pi  ## Charts ### Histogram matlab histogram(A) % where A is a vector of values histogram(A, 15) % place values in 15 groups  ### Bar matlab h = bar([1 2 4 8]); % create bar chart h.FaceColor = [0, 0.7 0]; % set properties  ## Plot options ### Hold (keep previous plots) matlab hold on plot(...)  ### Formatting Markers matlab plot(x, y, '.r'); % red dots plot(x, y, 'or'); % red circles plot(x, y, 'xr'); % red x plot(x, y, '*r'); % red stars  Lines matlab plot(x, y, '-'); % regular lines plot(x, y, ':'); % dotted lines plot(x, y, '--'); % dashed lines plot(x, y, '-.'); % dashed and dotted lines  Colors matlab plot(x, y, 'color', [0, 0.6, 0.2]); % RGB color  Line width matlab plot(x, y, 'LineWidth', 2); % set line width to 2 px  Marker color matlab plot(x, y, 'MarkerFaceColor', [0, 0.6, 0.2]); % RGB color of markers  Marker size matlab plot(x, y, 'MarkerSize', 7); % set marker size to 7 px  ### Legend and title matlab title('Title'); % number of names should match number and order of plots legend('First', 'Second', 'Third'); % legend with specific location legend('First', 'Second', 'Third', 'Location', 'northwest');  ### Labels matlab xlabel('\alpha'); % set x-label to α ylabel('y');  ### Axes matlab axis([XMIN XMAX YMIN YMAX]); % set scaling of both axes  ## Figures matlab fig = figure; % note: properties are case sensitive! fig = gcf; % get handle to current figure clf; % clear current figure  ### Typical object hierarchy mermaid graph TD Figure --> Legend Figure --> Axes Axes --> Lines  ### Set color matlab fig.Color = 'w'; % white fig.Color = [1.0 0.5 0.0]; % RGB  ### Plot handles matlab h = plot(x, y); % get handle h.LineWidth = 1.3; % modify properties h.Marker = '.'; % set marker  ### Sub-plots matlab fig = figure; subplot(2, 3, 1); % 2x3 matrix of plots, select first plot plot(x, y); % first plot subplot(2, 3, 2); % 2x3 matrix of plots, select second plot loglog(x, y); % second plot subplot(2, 3, 4); % 2x3 matrix of plots, select fourth plot semilogx(x, y); % second row, first plot subplot(2, 3, 6); % 2x3 matrix of plots, select last plot semilogy(x, y); % second row, third plot  Get handle matlab handle = subplot(2, 3, 1); % select first plot handle.Children(1).LineWidth = 2; % get line from handle and change width  ## 3-dimensional ### 3D-plot matlab plot3(x, y, z);  ### Surfaces Generate grid matlab % Generate grid from matrices with duplicate rows of x and duplicate columns of y [X Y] = meshgrid(x, y); % Matrices with dimension length(x) x length(y) mesh(X, Y) % Plot mesh Z = X.^2 - Y % use (uppercase!) X and Y to calculate Z mesh(X, Y, Z) % Plot mesh with Z coordinate  Mesh surface plot matlab mesh(X, Y) % Plot mesh (using X and Y from meshgrid) Z = X.^2 - Y % use (uppercase!) X and Y to calculate Z mesh(X, Y, Z) % Plot mesh with Z coordinate  Surface plot matlab surf(X, Y, Z) % Similar to mesh but always with Z coordinate  # Functions ## Regular functions ### Definition matlab % global function, always at the top of a file function file_name() % code... end % local function function FuncName() % code... end  ### Parameters matlab function funcName(param1, param2) disp(param1); % print param1 disp(param2); % print param2 end  Variable parameters matlab function funcName(param1, param2, varargin) % function takes at least two parameters for cnt = 1:length(varargin) arg = varargin{cnt}; % get one of the variable arguments if isnumeric(arg) % only print numeric values disp(arg); % print variable parameters else % ignore non-numeric values disp("Can't display non-numeric values"); end end end  ### Return values matlab function returnValue = duplicate(param) returnValue = [param param]; end value = duplicate(2) % value = [2 2] % multiple return values function [returnValue1, returnValue2] = funcName(param1, param2) returnValue1 = param1; returnValue2 = param2; end [value1, value2] = funcName(2, 3) % value1 = 2, value2 = 3  ### Documentation matlab function funcName() % This is a documentation comment % Explain what your function does here % This is a normal comment again end  ## Anonymous functions ### Get function handle matlab handle = @sin handle(1) % returns sin(1)  ### Define anonymous function matlab handle = @(param) 2 * cos(param * 2) % handle(1) returns 2*cos(2) handle = @(x) exp(x-x.^2) - 0.5  ## Function characteristics ### Zeros matlab fzero(handle, 1) % find a zero value starting from 1  ### Fit parameters matlab id = @(is,ud)is*exp(ud/0.05) % diode current is = lsqcurvefit(id, 1e-10, u, i); % find ideal value for is to fit measured values u and i  ## Differential equations ### First order matlab % transform the equation so that u' is separated du = @(t,u) -u/0.1; % u' = -u/0.1 U0 = 3; % start value tspan = [0 0.5]; % time span [t u] = ode45(du, tspan, U0); % calculate values  ### Higher order matlab % transform the equation so that y' = y1' and y'' = y2' are separated % y1' = y2 y2' = sin(100*t) - y1 - y2 dy = @(t,y) [ y(2) ; sin(100*t) - y(1) - y(2) ]; % c) [t y] = ode45(dy, [0 1], [1; 0]); % start at y1 = 1 and y2 = 0  ### Options matlab opts = odeset('absTol', 0.05); % set absolute error tolerance [t y] = ode45(@pendfun, tspan, yNull, opts);  # Transfer functions ## Create matlab G = tf([1 0], [2 0 0]);  ## Step response information matlab S = stepinfo(G);  ## Plot step response matlab orstep(G); step(G, 0.2);  ## Plot bode diagram matlab bode(G);  ## Plot nyquist diagram matlab nyquist(G);  # Control structures ## for-loop matlab for cnt = 1:5 % cnt can be any row vector fprintf(1, '%d\n', cnt); end  ## while-loop matlab cnt = 0; while cnt < 5 fprintf(1, '%d\n', cnt); cnt = cnt + 1; end  ## if-statement matlab cnt = 0; if cnt == 0 disp('Zero'); elseif mod(cnt, 2) == 0 disp('Even'); else disp('Odd'); end  Comparing vectors matlab vec1 = [1 2 3]; vec2 = [1 2 4]; vec1 == vec2 % 1×3 logical array % 1 1 0 if ~isequal(vec1, vec2) disp('Not equal') end  ## switch-statement matlab value = 4; switch value case 1 display("One"); case 2 display("Two"); case 3 display("Three"); otherwise display("Other number"); end  # Performance ## Time measurment matlab tic % start time measurement time = toc % take time measurement time2 = toc % take another time measurement (from same tic)  ## Solving linear equations matlab x = A\b; % fast, because optimized by Matlab x = inv(A)*b; % slow  ## Pre-allocating vectors matlab for cnt = 1:100 % inefficient, causes a lot of re-allocations a(cnt) = cnt; end b = zeros(1, 100); % pre-allocating memory for cnt = 1:100 a(cnt) = cnt; end  ### Real-world example matlab x = 0:0.01:150; y = zeros(size(x)); % initialized with zeros, same size as x cnt = 1; for i = x y(cnt) = sin(i); cnt = cnt + 1; end