**Fundamentals** - [[#Basic Syntax & Operations]] - [[#Variables & Data Types]] - [[#Arrays & Matrices]] **Math & Computing** - [[#Mathematical Operations]] - [[#Linear Algebra]] **Programming** - [[#Control Structures]] - [[#Functions]] **Data & Visualization** - [[#Plotting & Visualization]] - [[#File I/O]] - [[#String Manipulation]] - [[#Cell Arrays & Structures]] **Advanced** - [[#Advanced Topics]] - [[#Useful Built-in Functions]] - [[#Constants & Special Values]] ## Basic Syntax & Operations > [!note] Basic Commands > > ```matlab > clc % Clear command window > clear % Clear workspace variables > clear all % Clear all variables > close all % Close all figures > whos % Display workspace variables > help function % Get help for a function > doc function % Open documentation > ``` > [!tip] Command Line Tips > > ```matlab > % Comments start with % > %% Section break (for code folding) > ... % Continue statement on next line > ; % Suppress output > up arrow % Previous command > tab % Auto-complete > ``` ## Variables & Data Types > [!abstract] Variable Assignment > > ```matlab > x = 5; % Integer > y = 3.14; % Double (default) > z = 2 + 3i; % Complex number > str = 'hello'; % Character array > str2 = "world"; % String (R2017a+) > ``` > [!example] Data Types > > ```matlab > % Numeric Types > int8, int16, int32, int64 % Signed integers > uint8, uint16, uint32, uint64 % Unsigned integers > single % Single precision > double % Double precision (default) > > % Other Types > logical % Boolean (true/false) > char % Character array > string % String array > cell % Cell array > struct % Structure array > table % Table > ``` ## Arrays & Matrices > [!important] Array Creation > > ```matlab > % Row vector > v = [1 2 3 4]; > v = [1, 2, 3, 4]; > > % Column vector > v = [1; 2; 3; 4]; > > % Matrix > A = [1 2 3; 4 5 6; 7 8 9]; > > % Special arrays > zeros(m,n) % Matrix of zeros > ones(m,n) % Matrix of ones > eye(n) % Identity matrix > rand(m,n) % Random numbers [0,1] > randn(m,n) % Normal random numbers > linspace(a,b,n) % n points from a to b > logspace(a,b,n) % n logarithmically spaced points > ``` > [!warning] Array Indexing > > ```matlab > % MATLAB uses 1-based indexing > A(i,j) % Element at row i, column j > A(i,:) % Row i > A(:,j) % Column j > A(:) % All elements as column vector > A(end) % Last element > A(end-1) % Second to last element > A([1 3 5], :) % Rows 1, 3, 5 > A(A > 0) % Logical indexing > ``` > [!note] Array Operations > > ```matlab > % Element-wise operations (use .) > A .* B % Element-wise multiplication > A ./ B % Element-wise division > A .^ 2 % Element-wise square > > % Matrix operations > A * B % Matrix multiplication > A' % Transpose > A^2 % Matrix power > inv(A) % Matrix inverse > det(A) % Determinant > rank(A) % Matrix rank > ``` ## Mathematical Operations > [!formula] Basic Math Functions > > ```matlab > % Arithmetic > +, -, *, /, \, ^ % Basic operators > mod(x,y) % Modulo > rem(x,y) % Remainder > > % Powers and roots > sqrt(x) % Square root: $\sqrt{x}$ > nthroot(x,n) % nth root: $\sqrt[n]{x}$ > exp(x) % Exponential: $e^x$ > log(x) % Natural log: $\ln(x)$ > log10(x) % Base 10 log: $\log_{10}(x)$ > log2(x) % Base 2 log: $\log_2(x)$ > ``` > [!formula] Trigonometric Functions > > ```matlab > % Basic trig (input in radians) > sin(x), cos(x), tan(x) > asin(x), acos(x), atan(x) % Inverse trig > atan2(y,x) % Four-quadrant arctangent > > % Hyperbolic functions > sinh(x), cosh(x), tanh(x) > asinh(x), acosh(x), atanh(x) > > % Degree conversions > deg2rad(x) % Degrees to radians > rad2deg(x) % Radians to degrees > sind(x), cosd(x) % Trig functions with degree input > ``` > [!formula] Statistical Functions > > ```matlab > mean(x) % Arithmetic mean: $\bar{x} = \frac{1}{n}\sum_{i=1}^n x_i$ > median(x) % Median > mode(x) % Mode > std(x) % Standard deviation: $\sigma = \sqrt{\frac{1}{n-1}\sum_{i=1}^n(x_i-\bar{x})^2}$ > var(x) % Variance: $\sigma^2$ > min(x), max(x) % Minimum and maximum > sum(x) % Sum: $\sum_{i=1}^n x_i$ > prod(x) % Product: $\prod_{i=1}^n x_i$ > cumsum(x) % Cumulative sum > cumprod(x) % Cumulative product > ``` ## Linear Algebra > [!abstract] Matrix Operations > > ```matlab > % Matrix creation and manipulation > A = [1 2; 3 4]; > B = A'; % Transpose > C = A * B; % Matrix multiplication > > % Matrix properties > trace(A) % Trace: $\text{tr}(A) = \sum_{i=1}^n a_{ii}$ > det(A) % Determinant > rank(A) % Rank > norm(A) % Matrix norm > cond(A) % Condition number > ``` > [!important] Solving Linear Systems > > ```matlab > % Solve Ax = b > x = A \ b; % Left matrix division (preferred) > x = inv(A) * b; % Using inverse (less efficient) > x = linsolve(A, b); % General linear system solver > > % Least squares solution (overdetermined system) > x = A \ b; % MATLAB automatically uses least squares > x = pinv(A) * b; % Using pseudoinverse > ``` > [!note] Eigenvalues and Eigenvectors > > ```matlab > % Eigenvalue decomposition: $A\mathbf{v} = \lambda\mathbf{v}$ > [V, D] = eig(A); % V: eigenvectors, D: eigenvalues > lambda = eig(A); % Eigenvalues only > > % Singular Value Decomposition: $A = U\Sigma V^T$ > [U, S, V] = svd(A); > ``` ## Control Structures > [!gear] Conditional Statements > > ```matlab > % if-else > if condition > statements > elseif condition2 > statements > else > statements > end > > % switch-case > switch variable > case value1 > statements > case {value2, value3} > statements > otherwise > statements > end > ``` > [!gear] Loops > > ```matlab > % for loop > for i = 1:n > statements > end > > for i = 1:2:10 % Step by 2 > statements > end > > for i = [1 3 7 9] % Specific values > statements > end > > % while loop > while condition > statements > end > ``` > [!tip] Loop Control > > ```matlab > break % Exit loop > continue % Skip to next iteration > return % Exit function > ``` ## Functions > [!code] Function Definition > > ```matlab > % Function file: myfunction.m > function [output1, output2] = myfunction(input1, input2) > % Function documentation > % Compute something > output1 = input1 * 2; > output2 = input2 + 1; > end > > % Anonymous functions > f = @(x) x.^2 + 2*x + 1; % f(x) = x² + 2x + 1 > g = @(x,y) x.*y + sin(x); % Multiple inputs > ``` > [!example] Function Features > > ```matlab > % Variable arguments > function result = mysum(varargin) > result = sum([varargin{:}]); > end > > % Default arguments (use nargin) > function result = power_func(x, n) > if nargin < 2 > n = 2; % Default power > end > result = x.^n; > end > > % Nested functions > function main_function() > x = 5; > nested_function(); > > function nested_function() > y = x * 2; % Can access parent variables > end > end > ``` ## Plotting & Visualization > [!chart] 2D Plotting > > ```matlab > % Basic plotting > x = 0:0.1:2*pi; > y = sin(x); > plot(x, y); % Line plot > > % Plot customization > plot(x, y, 'r--', 'LineWidth', 2); % Red dashed line > xlabel('x'); ylabel('y'); > title('Sine Function'); > legend('sin(x)'); > grid on; > axis([0 2*pi -1 1]); % Set axis limits > > % Multiple plots > hold on; % Keep current plot > plot(x, cos(x), 'b:'); > hold off; > > % Subplots > subplot(2, 1, 1); plot(x, sin(x)); > subplot(2, 1, 2); plot(x, cos(x)); > ``` > [!chart] Plot Types > > ```matlab > % Different plot types > scatter(x, y); % Scatter plot > bar(x, y); % Bar chart > histogram(data); % Histogram > boxplot(data); % Box plot > errorbar(x, y, err); % Error bars > semilogx(x, y); % Semi-log plot (log x-axis) > semilogy(x, y); % Semi-log plot (log y-axis) > loglog(x, y); % Log-log plot > polar(theta, rho); % Polar plot > ``` > [!chart] 3D Plotting > > ```matlab > % 3D plots > x = -2:0.1:2; y = x; > [X, Y] = meshgrid(x, y); > Z = X.^2 + Y.^2; > > surf(X, Y, Z); % Surface plot > mesh(X, Y, Z); % Mesh plot > contour(X, Y, Z); % Contour plot > plot3(x, y, z); % 3D line plot > scatter3(x, y, z); % 3D scatter plot > ``` ## File I/O > [!file] Reading/Writing Data > > ```matlab > % Text files > data = readmatrix('data.csv'); % Read numeric data > T = readtable('data.csv'); % Read as table > writematrix(data, 'output.csv'); % Write numeric data > writetable(T, 'output.csv'); % Write table > > % Excel files > data = readmatrix('file.xlsx'); > T = readtable('file.xlsx', 'Sheet', 'Sheet1'); > writematrix(data, 'output.xlsx'); > > % MATLAB files > save('data.mat', 'variable1', 'variable2'); > load('data.mat'); % Load all variables > load('data.mat', 'variable1'); % Load specific variable > ``` > [!file] Low-level File I/O > > ```matlab > % Text file I/O > fileID = fopen('filename.txt', 'r'); % Open for reading > data = fscanf(fileID, '%f'); % Read formatted data > fclose(fileID); % Close file > > % Writing > fileID = fopen('output.txt', 'w'); % Open for writing > fprintf(fileID, 'Value: %f\n', value); % Write formatted data > fclose(fileID); > ``` ## String Manipulation > [!text] String Operations > > ```matlab > % String arrays (R2017a+) > str = "Hello World"; > str_array = ["apple", "banana", "cherry"]; > > % String functions > length(str) % String length > upper(str) % Uppercase > lower(str) % Lowercase > strip(str) % Remove whitespace > contains(str, "Hello") % Check if contains substring > startsWith(str, "He") % Check if starts with > endsWith(str, "ld") % Check if ends with > split(str, " ") % Split string > join(str_array, ", ") % Join strings > ``` > [!text] Character Arrays (Legacy) > > ```matlab > % Character array operations > str = 'Hello World'; > strcmp(str1, str2) % Compare strings > strncmp(str1, str2, n) % Compare first n characters > strfind(str, pattern) % Find pattern in string > strrep(str, old, new) % Replace substring > sprintf('Value: %d', x) % Format string > ``` ## Cell Arrays & Structures > [!database] Cell Arrays > > ```matlab > % Cell array creation > C = {'apple', 123, [1 2 3]}; % Mixed data types > C = cell(3, 2); % Preallocate empty cell array > > % Cell array indexing > C{1} = 'new value'; % Content indexing > C(1) = {'another value'}; % Cell indexing > > % Useful cell functions > cellfun(@length, C); % Apply function to each cell > cell2mat(C); % Convert to matrix (if possible) > ``` > [!database] Structures > > ```matlab > % Structure creation > student.name = 'John'; > student.age = 20; > student.grades = [85, 90, 78]; > > % Alternative creation > student = struct('name', 'John', 'age', 20, 'grades', [85 90 78]); > > % Structure arrays > students(1).name = 'John'; > students(2).name = 'Jane'; > > % Structure functions > fieldnames(student); % Get field names > isfield(student, 'age'); % Check if field exists > rmfield(student, 'age'); % Remove field > ``` ## Advanced Topics > [!cog] Object-Oriented Programming > > ```matlab > % Class definition (in separate file) > classdef MyClass < handle > properties > Value > end > > methods > function obj = MyClass(val) > obj.Value = val; > end > > function result = compute(obj) > result = obj.Value * 2; > end > end > end > > % Usage > obj = MyClass(5); > result = obj.compute(); > ``` > [!warning] Error Handling > > ```matlab > % try-catch blocks > try > result = risky_operation(); > catch ME > fprintf('Error: %s\n', ME.message); > result = default_value; > end > > % Throwing errors > if x < 0 > error('x must be non-negative'); > end > > warning('This is a warning message'); > ``` > [!zap] Performance Tips > > ```matlab > % Preallocate arrays > data = zeros(1000, 1); % Good > % data = []; data(end+1) = x; % Bad (growing arrays) > > % Vectorize operations > y = sin(x); % Good (vectorized) > % for i=1:length(x); y(i)=sin(x(i)); end % Bad (loop) > > % Use built-in functions > sum(x) % Good > % total = 0; for i=1:n; total=total+x(i); end % Slower > > % Profile code > profile on > your_code(); > profile viewer > ``` ## Useful Built-in Functions > [!tool] Array Manipulation > > ```matlab > size(A) % Array dimensions > length(A) % Length of largest dimension > numel(A) % Number of elements > reshape(A, m, n) % Reshape array > repmat(A, m, n) % Replicate array > flipud(A) % Flip up-down > fliplr(A) % Flip left-right > rot90(A) % Rotate 90 degrees > sort(A) % Sort array > unique(A) % Unique elements > find(condition) % Find indices where condition is true > ``` > [!tool] Interpolation & Approximation > > ```matlab > % Interpolation > yi = interp1(x, y, xi); % 1D interpolation > zi = interp2(x, y, z, xi, yi); % 2D interpolation > > % Polynomial fitting > p = polyfit(x, y, n); % Fit polynomial of degree n > y_fit = polyval(p, x); % Evaluate polynomial > > % Curve fitting > f = fit(x, y, 'poly2'); % Fit quadratic polynomial > ``` > [!tool] Optimization > > ```matlab > % Find minimum > [x_min, f_min] = fminbnd(@(x) x^2, -1, 1); % Bounded 1D > [x_min, f_min] = fminsearch(@(x) sum(x.^2), [1 1]); % Unconstrained > > % Root finding > root = fzero(@(x) x^2 - 4, 1); % Find zero near x=1 > ``` ## Constants & Special Values > [!info] Mathematical Constants > > ```matlab > pi % π ≈ 3.14159 > exp(1) % e ≈ 2.71828 (Euler's number) > i, j % Imaginary unit: √(-1) > inf % Infinity > -inf % Negative infinity > NaN % Not a Number > eps % Machine epsilon (floating-point precision) > realmax % Largest finite floating-point number > realmin % Smallest positive floating-point number > ``` > [!tip] Quick Reference Shortcuts > > - `Ctrl+C`: Interrupt execution > - `Ctrl+R`: Comment selection > - `Ctrl+T`: Uncomment selection > - `F5`: Run script > - `F9`: Run selection > - `Tab`: Auto-complete > - `↑/↓`: Command history