1. MATLAB Basics 1.1. Environment & Workflow Command Window: Main interface for commands. >> : Command prompt. Up/Down Arrow: Recall previous commands. ... : Continue long commands on next line. ; : Suppress output display. % : Comment (single line). clc : Clears Command Window. Workspace: Stores variables. who : Lists variables in memory. whos : Lists variables with size, bytes, class. clear : Clears all variables. clear x y z : Clears specific variables. Editor Window: For creating/editing script and function files. Figure Window: Displays plots. Current Folder: MATLAB's working directory. cd 'path' : Change directory. 1.2. Arithmetic Operations (Scalars) Addition: + Subtraction: - Multiplication: * Right Division: / Left Division: \ (e.g., $5 \backslash 3 = 3/5$) Exponentiation: ^ Order of Precedence: Parentheses > Exponentiation > Multiplication/Division > Addition/Subtraction. 1.3. Display Formats format short : Fixed-point, 4 decimal digits (default). format long : Fixed-point, 15 decimal digits. format short e : Scientific notation, 4 decimal digits. format long e : Scientific notation, 15 decimal digits. format bank : Two decimal digits. format compact : Suppresses empty lines. format loose : Adds empty lines. 1.4. Elementary Math Functions sqrt(x) : Square root. nthroot(x,n) : Real $n$-th root. exp(x) : Exponential $e^x$. abs(x) : Absolute value. log(x) : Natural logarithm (base $e$). log10(x) : Base 10 logarithm. factorial(x) : Factorial $x!$. Trigonometric (radians): sin(x) , cos(x) , tan(x) , cot(x) , asin(x) , acos(x) , atan(x) , acot(x) . Trigonometric (degrees): sind(x) , cosd(x) , tand(x) , cotd(x) , asind(x) , acosd(x) , atand(x) , acotd(x) . Hyperbolic: sinh(x) , cosh(x) , tanh(x) , coth(x) . Rounding: round(x) : Nearest integer. fix(x) : Towards zero. ceil(x) : Towards infinity. floor(x) : Towards minus infinity. rem(x,y) : Remainder after division. sign(x) : Signum function. 1.5. Variables Assignment: variable_name = value (e.g., x = 5 ). Rules: Start with a letter. Max 63 characters. Letters, digits, underscore. Case-sensitive ( AA $\neq$ Aa ). No spaces. Avoid built-in function names. Predefined: ans : Last unassigned result. pi : $\pi$. eps : Floating-point relative precision. inf : Infinity. i , j : Imaginary unit. NaN : Not-a-Number. Keywords: Reserved words (e.g., if , for , end ). Cannot be variable names. 1.6. Script Files (.m files) Sequence of MATLAB commands. Executed sequentially. Can be edited and re-run. Creation: Editor Window > File > New > Script. Saving: .m extension (e.g., my_script.m ). Running: Type filename in Command Window, or click "Run" in Editor. 2. Arrays 2.1. Creating Arrays Row Vector: v = [e1 e2 e3] or v = [e1, e2, e3] . Column Vector: v = [e1; e2; e3] or v = [e1; e2; e3] (pressing Enter after each element). Constant Spacing: v = m:q:n : Start $m$, increment $q$, end $n$. v = m:n : Increment 1 (default). Linear Spacing: v = linspace(xi, xf, n) : $n$ elements between $xi$ and $xf$. Matrix: M = [r1c1 r1c2; r2c1 r2c2] (semicolon for new row). Special Matrices: zeros(m,n) : $m \times n$ matrix of zeros. ones(m,n) : $m \times n$ matrix of ones. eye(n) : $n \times n$ identity matrix. 2.2. Array Addressing Vector: v(k) : $k$-th element. Matrix: M(k,p) : Element in row $k$, column $p$. Colon Operator: v(:) : All elements of vector $v$. v(m:n) : Elements $m$ through $n$. M(:,n) : All rows of column $n$. M(n,:) : All columns of row $n$. M(m:n,p:q) : Elements in rows $m$ to $n$, columns $p$ to $q$. Specific Elements/Rows/Cols: v([i1 i2 i3]) or M([r1 r2],[c1 c2]) . 2.3. Modifying Arrays Adding Elements: Assign to new index (fills with zeros if skipped indices). Adding Vectors/Matrices: Append using square brackets (sizes must match). Deleting Elements: Assign empty brackets [] (e.g., v(k)=[] ). 2.4. Array Operations (Linear Algebra) Addition/Subtraction: A + B , A - B (arrays must be same size). Scalar addition/subtraction applies to all elements. Multiplication: A * B (inner dimensions must agree). Row vector * Column vector = Scalar (dot product). Column vector * Row vector = Matrix. Scalar * Array: Multiplies each element. Division: Left Division ($\backslash$): X = A \ B solves $AX=B$. Right Division (/): X = D / C solves $XC=D$. Transpose: A' (swaps rows and columns). Inverse: inv(A) (for square, non-singular matrices). Determinant: det(A) . 2.5. Element-by-Element Operations Apply a period ( . ) before the operator. Requires arrays of the same size. A .* B : Element-by-element multiplication. A ./ B : Element-by-element right division. A .\ B : Element-by-element left division. A .^ n : Element-by-element exponentiation. 2.6. Built-in Array Functions length(v) : Number of elements in vector $v$. size(A) : Returns `[m, n]` for $m \times n$ array. reshape(A, m, n) : Reshapes matrix $A$ to $m \times n$. max(A) , min(A) : Max/min value (vector) or row vector of max/min of each column (matrix). [d,n]=max(A) : Value $d$ and index $n$. sum(A) : Sum of elements (vector) or row vector of column sums (matrix). mean(A) : Mean of elements (vector) or row vector of column means (matrix). median(A) : Median value. std(A) : Standard deviation. sort(A) : Sorts elements in ascending order. dot(a,b) : Dot product of vectors $a, b$. cross(a,b) : Cross product of 3D vectors $a, b$. 2.7. Strings Created with single quotes: 'Hello World' . Can be assigned to variables. Each character (including space) is an element in a row vector. char('str1', 'str2') : Creates a character array, padding shorter strings with spaces. 3. Input/Output & Data Management 3.1. User Input variable = input('prompt message') : Prompts for numerical input. variable = input('prompt message', 's') : Prompts for string input. 3.2. Output Commands disp(variable) : Displays variable content without name. disp('text as string') : Displays text message. fprintf('text %format_specifier additional text', variable) : Formatted output. \n : New line. \t : Tab. %f : Fixed-point (default 6 decimal places). %e : Scientific notation (lowercase 'e'). %E : Scientific notation (uppercase 'E'). %g : Shorter of %e or %f . %i : Integer. %s : String. %nd : $n$ digits wide, integer. %n.mf : $n$ digits wide, $m$ decimal places fixed-point. %n.me : $n$ digits wide, $m$ decimal places scientific. 3.3. Saving & Loading Data MAT-files (.mat): Binary format, preserves variable names/types. save filename : Saves all workspace variables to filename.mat . save filename var1 var2 : Saves specific variables. load filename : Loads variables from filename.mat . load filename var1 var2 : Loads specific variables. ASCII files: Text format, data only (no variable info). save filename -ascii : Saves all variables (numerical) to filename . load filename.txt : Loads data from filename.txt into a variable named filename . mydata = load('filename.txt') : Loads data into mydata . 3.4. Importing & Exporting Data (Excel) data = xlsread('filename.xlsx') : Reads data from Excel sheet 1. data = xlsread('filename.xlsx', 'SheetName') : Reads from specified sheet. data = xlsread('filename.xlsx', 'SheetName', 'A1:C5') : Reads from specified range. xlswrite('filename.xlsx', data) : Writes data to Excel (sheet 1). xlswrite('filename.xlsx', data, 'SheetName', 'A1') : Writes to specified sheet/cell. Import Wizard: Graphical tool ( uiimport or File > Import Data). 4. 2D Plots 4.1. Basic Plotting ( plot ) plot(x, y) : Plots $y$ vs. $x$ with default settings. plot(x, y, 'line_specifiers', 'PropertyName', PropertyValue) : Customize plot. Line Specifiers: Line Style: - (solid), -- (dashed), : (dotted), -. (dash-dot). Color: r , g , b , c , m , y , k , w . Marker: + , o , * , . , x , s (square), d (diamond), ^ (up triangle), etc. Property Name/Value Pairs: 'LineWidth', value : Line thickness. 'MarkerSize', value : Marker size. 'MarkerEdgeColor', color : Marker edge color. 'MarkerFaceColor', color : Marker fill color. 4.2. Plotting Functions ( fplot ) fplot('function_string', [xmin, xmax]) : Plots function over $x$ range. fplot('function_string', [xmin, xmax, ymin, ymax]) : Specify $x$ and $y$ limits. 4.3. Multiple Graphs on One Plot Using plot : plot(x1, y1, 'spec1', x2, y2, 'spec2', ...) . Using hold on / hold off : plot(x1, y1); hold on; plot(x2, y2); hold off; Using line : line(x, y, 'PropertyName', PropertyValue) (adds to existing plot). 4.4. Plot Formatting Commands xlabel('text') , ylabel('text') , zlabel('text') . title('text') . text(x, y, 'text') : Places text at $(x, y)$. gtext('text') : Places text interactively with mouse. legend('label1', 'label2', ..., pos) : Creates a legend. pos = -1 : Outside right. pos = 0 : Best fit inside. pos = 1 : Upper-right (default). pos = 2 : Upper-left. pos = 3 : Lower-left. pos = 4 : Lower-right. Text Formatting (in strings): \bf : Bold, \it : Italic, \rm : Normal. \fontname{name} , \fontsize{size} . _ : Subscript, ^ : Superscript. Greek letters: \alpha , \beta , \gamma , \theta , \pi . Axis Control: axis([xmin, xmax, ymin, ymax]) : Sets axis limits. axis equal : Equal scale for axes. axis square : Square plot region. axis tight : Limits to data range. grid on / grid off : Toggles grid lines. 4.5. Logarithmic Axes semilogy(x, y) : Log scale for y-axis. semilogx(x, y) : Log scale for x-axis. loglog(x, y) : Log scale for both axes. 4.6. Error Bars errorbar(x, y, e) : Symmetric error bars ($y \pm e$). errorbar(x, y, d, u) : Asymmetric error bars ($y - d$ to $y + u$). 4.7. Specialized 2D Plots bar(x, y) : Vertical bar chart. barh(x, y) : Horizontal bar chart. stairs(x, y) : Stairs plot. stem(x, y) : Stem plot. pie(x) : Pie chart. hist(y) : Histogram (10 bins). hist(y, nbins) : Histogram ($nbins$ bins). hist(y, xcenters) : Histogram with specified bin centers. polar(theta, radius) : Polar plot. 4.8. Multiple Figure Windows figure : Opens a new figure window (e.g., Figure 2). figure(n) : Makes figure $n$ current (opens if not exists). close : Closes current figure. close(n) : Closes figure $n$. close all : Closes all figures. subplot(m, n, p) : Divides figure into $m \times n$ grid, activates $p$-th subplot. 5. User-Defined Functions 5.1. Function Files (.m files) Definition Line: function [out1, out2] = func_name(in1, in2) function is first word. func_name should match filename. Input/output arguments are local to the function. H1 Line: First comment line, brief summary. Used by lookfor . Help Text: Comments after H1 line. Displayed by help func_name . Function Body: MATLAB code for calculations. Local Variables: All variables within a function are local (not shared with workspace). Global Variables: global VAR_NAME (must be declared in all relevant functions and workspace). Saving: Filename must match function name. Using: Call like built-in functions (e.g., [res1, res2] = my_function(val1, val2) ). 5.2. Anonymous Functions Single-line functions defined without a separate file. func_handle = @(input_args) expression (e.g., f = @(x) x.^2 + 1 ). Can capture values of variables existing at time of creation. 5.3. Inline Functions (Older, mostly replaced by Anonymous) func_name = inline('expression', 'var1', 'var2') . 5.4. Function Functions Functions that accept other functions as input arguments. Function Handles: Preferred method. Create handle: @function_name (for user-defined/built-in) or anonymous function name. Pass handle: my_func_func(@my_func, ...) . Using Function Name (as string): Older method, uses feval . feval('function_name', args) . 5.5. Subfunctions & Nested Functions Subfunctions: Multiple functions in one file. First is primary, others are subfunctions. Only primary function callable from outside. Each has its own workspace. Nested Functions: Function defined inside another function. Nested function can access parent's workspace. Parent function can access nested function's workspace. Requires end statement for each function. 6. Programming & Flow Control 6.1. Relational Operators < : Less than. > : Greater than. <= : Less than or equal to. >= : Greater than or equal to. == : Equal to. ~= : Not equal to. Result is 1 (true) or 0 (false). Element-by-element for arrays. 6.2. Logical Operators & : AND (both true). | : OR (either true). ~ : NOT (opposite). Operate on non-zero (true) and zero (false). Built-in Logical Functions: and(A,B) , or(A,B) , not(A) , xor(A,B) , all(A) , any(A) , find(A) . Precedence: Parentheses > Exponentiation > NOT > Mult/Div > Add/Sub > Relational > AND > OR. 6.3. Conditional Statements if-end : if condition % commands end if-else-end : if condition % commands if true else % commands if false end if-elseif-else-end : if condition1 % commands for condition1 elseif condition2 % commands for condition2 else % commands if neither is true end 6.4. switch-case Statement switch switch_expression case value1 % commands case {value2a, value2b} % multiple values % commands otherwise % commands end 6.5. Loops for-end Loop: Known number of iterations. for index = start:increment:end % commands end while-end Loop: Unknown number of iterations, continues until condition is false. while condition % commands end break : Terminates loop execution. continue : Skips current iteration, proceeds to next. Nested Loops/Conditionals: Loops/conditionals inside others. 7. Polynomials 7.1. Representation Row vector of coefficients in descending order of power. e.g., $3x^2 + 2x - 5 \rightarrow [3 \ 2 \ -5]$ Include zeros for missing powers. e.g., $x^3 + 7 \rightarrow [1 \ 0 \ 0 \ 7]$ 7.2. Operations polyval(p, x) : Evaluates polynomial $p$ at $x$. ($x$ can be scalar, vector, or matrix). roots(p) : Finds roots of polynomial $p$. poly(r) : Finds coefficients of polynomial from roots $r$. conv(p1, p2) : Multiplies polynomials $p1$ and $p2$. [q, r] = deconv(p1, p2) : Divides $p1$ by $p2$, returning quotient $q$ and remainder $r$. polyder(p) : Differentiates polynomial $p$. polyder(p1, p2) : Differentiates product $p1 \cdot p2$. [n, d] = polyder(num, den) : Differentiates quotient $num/den$. 8. Curve Fitting & Interpolation 8.1. Curve Fitting polyfit(x, y, n) : Fits a polynomial of degree $n$ to data $(x, y)$ using least squares. Returns coefficients. Fitting non-polynomials: Linearize by transforming variables (e.g., $\ln y$ vs. $x$ for exponential $y=be^{mx}$). Power: $y=bx^m \implies \ln y = m \ln x + \ln b$ Exponential: $y=be^{mx} \implies \ln y = mx + \ln b$ Logarithmic: $y=m \ln x + b$ Reciprocal: $y=1/(mx+b) \implies 1/y = mx+b$ 8.2. Interpolation yi = interp1(x, y, xi, 'method') : Interpolates $y$ values at $xi$. 'nearest' : Nearest neighbor. 'linear' : Linear interpolation (default). 'spline' : Cubic spline interpolation. 'pchip' : Piecewise cubic Hermite interpolation. 8.3. Basic Fitting Interface Interactive tool for curve fitting and interpolation (Tools > Basic Fitting). Allows selecting fit type, displaying equations, residuals, and evaluating points. 9. Numerical Analysis 9.1. Solving Equations (Single Variable) x = fzero(@function_handle, x0) : Finds a root of $f(x)=0$ near $x0$. @function_handle : Can be string, user-defined function handle, or anonymous function handle. x0 : Initial guess (scalar) or interval [x1, x2] where $f(x1)$ and $f(x2)$ have opposite signs. 9.2. Finding Minima/Maxima of a Function x = fminbnd(@function_handle, x1, x2) : Finds local minimum of $f(x)$ in $[x1, x2]$. To find maximum, find minimum of -f(x) . 9.3. Numerical Integration For functions: q = quad(@function_handle, a, b) : Adaptive Simpson method. q = quadl(@function_handle, a, b) : Adaptive Lobatto method (often better for smooth functions). For data points: q = trapz(x, y) : Trapezoidal numerical integration. 9.4. Ordinary Differential Equations (ODEs) Standard Form: $\frac{dy}{dt} = f(t, y)$ for $t_0 \le t \le t_f$, with $y(t_0) = y_0$. Steps: Define $f(t, y)$ as a user-defined function (e.g., dydt = myODE(t, y) ) or an anonymous function. Choose an ODE solver: ode45 : Nonstiff problems (most common, good first choice). ode23 : Nonstiff (less accurate, faster). ode113 : Nonstiff (multistep). ode15s , ode23s , ode23t , ode23tb : Stiff problems. Solve: [t, y] = solver_name(@myODE, tspan, y0) tspan : Vector [t0 tf] or [t0 t1 ... tf] . y0 : Initial value of $y$. Outputs $t$ (column vector of time points) and $y$ (column vector of solutions). 10. 3D Plots 10.1. Line Plots plot3(x, y, z, 'line_specifiers', 'PropertyName', PropertyValue) : Connects points $(x_i, y_i, z_i)$. 10.2. Mesh & Surface Plots (for $z = f(x, y)$) Create Grid: [X, Y] = meshgrid(x_vector, y_vector) . Calculate Z: Z = f(X, Y) (use element-by-element operations). Plot: mesh(X, Y, Z) : Wireframe mesh. surf(X, Y, Z) : Colored surface with mesh. meshz(X, Y, Z) : Mesh with curtain. meshc(X, Y, Z) : Mesh with 2D contour beneath. surfc(X, Y, Z) : Surface with 2D contour beneath. surfl(X, Y, Z) : Surface with lighting effects. waterfall(X, Y, Z) : Mesh in one direction only. Contour Plots: contour3(X, Y, Z, n) : 3D contour lines. contour(X, Y, Z, n) : 2D contour projection. Polar Coordinates Grid ($z = f(r, \theta)$): [TH, R] = meshgrid(theta_vector, r_vector) . Z = f(R, TH) . [X, Y] = pol2cart(TH, R) : Convert to Cartesian. Plot using mesh(X, Y, Z) or surf(X, Y, Z) . 10.3. View Control view(azimuth, elevation) : Sets camera angle. azimuth : Angle in $xy$-plane from negative $y$-axis (counter-clockwise). elevation : Angle from $xy$-plane (positive upwards). Defaults: az = -37.5 , el = 30 . Projections: Top View ($xy$-plane): view(0, 90) or view(2) . Side View ($xz$-plane): view(0, 0) . Side View ($yz$-plane): view(90, 0) . view([x, y, z]) : Sets view from point $(x, y, z)$ towards origin. 11. Symbolic Math 11.1. Symbolic Objects & Expressions Creating Symbolic Variables: syms x y z : Creates multiple symbolic variables. x = sym('x') : Creates a single symbolic variable. Creating Symbolic Numbers: s_num = sym(5) . Creating Symbolic Expressions: Combine symbolic variables/numbers. e.g., f = x^2 + 2*y - 3 . Calculations are exact. double(S) : Converts symbolic expression $S$ to numerical (double-precision). findsym(S) : Lists symbolic variables in expression $S$ (alphabetical). findsym(S, n) : Lists $n$ symbolic variables (default order). 11.2. Changing Expression Form collect(S) : Collects coefficients of like powers in $S$. collect(S, var) : Collects coefficients with respect to variable $var$. expand(S) : Expands products and applies identities. factor(S) : Factors polynomial $S$. simplify(S) : Simplifies $S$ using algebraic/trig identities. simple(S) : Finds shortest form of $S$ (tries various simplifications). pretty(S) : Displays $S$ in a typeset-like format. 11.3. Solving Algebraic Equations h = solve(eq) : Solves $eq=0$ for default symbolic variable. h = solve(eq, var) : Solves $eq=0$ for variable $var$. h = solve('equation_string') : Equation as string. System of Equations: [var1, var2] = solve(eq1, eq2) : Outputs as cell array. S = solve(eq1, eq2) : Outputs as structure (access with S.var1 ). 11.4. Differentiation diff(S) : Differentiates $S$ with respect to default symbolic variable. diff(S, var) : Differentiates $S$ with respect to $var$. diff(S, n) : $n$-th derivative of $S$. diff(S, var, n) : $n$-th derivative of $S$ with respect to $var$. 11.5. Integration int(S) : Indefinite integral of $S$ with respect to default symbolic variable. int(S, var) : Indefinite integral of $S$ with respect to $var$. int(S, a, b) : Definite integral of $S$ from $a$ to $b$. int(S, var, a, b) : Definite integral of $S$ with respect to $var$ from $a$ to $b$. 11.6. Solving Ordinary Differential Equations (ODEs) dsolve('equation_string') : Solves ODE for default independent variable (t). D : First derivative (e.g., Dy for $dy/dt$). D2 : Second derivative (e.g., D2y for $d^2y/dt^2$). Constants of integration: C1, C2, ... . dsolve('equation_string', 'independent_var_string') : Specify independent variable. Particular Solutions: Include boundary/initial conditions. dsolve('eq', 'y(a)=A') . dsolve('eq', 'Dy(a)=A') . 11.7. Plotting Symbolic Expressions ezplot(S) : Plots symbolic expression $S$. One variable: $y=S(var)$ vs. $var$. Two variables: $S(var1, var2)=0$ (plots implicit function). Default domain: $[-2\pi, 2\pi]$ for variables. ezplot(S, [min, max]) or ezplot(S, [xmin, xmax, ymin, ymax]) : Specify plot limits. Parametric Plots: ezplot(S1, S2) or ezplot(S1, S2, [min, max]) : Plots $S2$ vs. $S1$ where $S1, S2$ are functions of a common parameter.