| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581 |
- MATLAB Midterm Cheat Sheet
- Oct 10, 2026 · @Abhimanyu Varma
- Ctrl+F keyword index
- Search the keyword in the left column to jump to working code. Every code block runs as-
- is in MATLAB; change the numbers to match the exam question.
- If the question says... Ctrl+F this
- make a vector / range / evenly spaced points LINSPACE
- zeros, ones, identity, random matrix MAKEMATRIX
- size, number of elements SIZEOF
- multiply element by element, square each element DOTOPS
- get an element, row, column INDEXING
- find where a value is, max/min location FINDVALUE
- submatrix, extract block SUBMATRIX
- add a row/column, delete a row/column ADDDELETE
- repeat / tile a matrix, reshape REPMAT
- sort, sum, mean, transpose MATRIXFUNCS
- plot, labels, legend, multiple curves, subplot PLOTTING
- for loop, while loop, if/else LOOPS
- play a note, play music, sound, frequency MUSIC
- anonymous function, @(x) ANONYMOUS
- function file, M-file, multiple outputs MFILE
- find a root, minimum, integral of a function FZERO
- basketball, projectile, launch angle, animate BASKETBALL
- linear equations, Ax = b, circuit, Kirchhoff, mesh MESH
- MATLAB Midterm Cheat Sheet
- Page 1 of 17
- Basics: variables, vectors, matrices
- End a line with ; to hide output; leave it off to print the result. % starts a comment. clc
- clears the screen, clear clears variables, close all closes figures.
- LINSPACE / ranges
- x = 1:5 % [1 2 3 4 5]
- x = 0:0.5:2 % start:step:stop -> [0 0.5 1 1.5 2]
- x = 10:-2:0 % counting down -> [10 8 6 4 2 0]
- x = linspace(0, 2*pi, 20) % 20 evenly spaced points from 0 to 2pi
- r = [1 2 3] % row vector
- c = [1; 2; 3] % column vector (semicolons = new row)
- c = r' % transpose row -> column
- MAKEMATRIX
- A = [1 2 3; 4 5 6; 7 8 9] % 3x3, rows separated by ;
- Z = zeros(3,4) % 3 rows, 4 cols of 0
- O = ones(2,3) % all 1s
- I = eye(3) % 3x3 identity
- R = rand(3) % 3x3 random in (0,1)
- Ri = randi(10,3,3) % random integers 1..10, 3x3
- D = diag([1 2 3]) % diagonal matrix from a vector
- d = diag(A) % pull the diagonal out of a matrix
- M = magic(4) % handy test matrix
- SIZEOF
- If the question says... Ctrl+F this
- eigenvalues, eigenvectors, eig EIGEN
- quantum well, Schrodinger, Hamiltonian, energy
- levels
- QUANTUM
- error message ERRORS
- MATLAB Midterm Cheat Sheet
- Page 2 of 17
- [rows, cols] = size(A) % both dimensions
- size(A,1) % number of rows
- size(A,2) % number of columns
- length(x) % longest dimension (use for vectors)
- numel(A) % total number of elements
- DOTOPS (the most common exam mistake)
- A * B % matrix multiplication (inner dims must match)
- A .* B % element-by-element multiply (same size)
- A ./ B % element-by-element divide
- A .^ 2 % square every element
- A ^ 2 % A*A (matrix power, square matrices only)
- A' % transpose
- 2*A, A+3 % scalar ops work element-wise automatically
- Rule: if x is a vector and you write a formula in it, use .* , ./ , .^ everywhere. Example:
- y = exp(-0.2*x).*sin(6*x);
- Useful built-ins: sqrt , exp , log (natural), log10 , abs , sin/cos/tan (radians),
- sind/cosd/tand (degrees), asin/atan , atan2(y,x) , round , floor , ceil , mod(a,b) ,
- pi . Degrees to radians: deg2rad(d) , back: rad2deg(r) .
- Printing nicely
- disp(x) % print a value
- fprintf('I1 = %.4f A\n', I1) % 4 decimals, then newline
- fprintf('Angle = %.2f deg, v = %.3f m/s\n', th, v)
- format long % show more digits; format short to go back
- Manipulating matrices
- Indexing is always A(row, col) , starting at 1. : means "all", end means "last".
- INDEXING
- MATLAB Midterm Cheat Sheet
- Page 3 of 17
- A = [1 2 3; 4 5 6; 7 8 9];
- A(2,3) % row 2, col 3 -> 6
- A(2,:) % entire row 2 -> [4 5 6]
- A(:,1) % entire column 1 -> [1;4;7]
- A(end,end) % last element -> 9
- A(end,:) % last row
- A(5) % linear index: counts DOWN columns -> 5
- x(3) % 3rd element of a vector
- x(end-1) % second to last
- A(2,3) = 100 % change one element
- A(:,2) = 0 % set whole column 2 to zero
- FINDVALUE (locate a number)
- idx = find(x == 5) % positions where x equals 5
- idx = find(x > 3) % positions where condition true
- [r, c] = find(A == 6) % row and column of value 6 in matrix
- [r, c] = find(A > 5) % all rows/cols matching
- [m, i] = max(x) % max value and its index
- [m, i] = min(x) % min value and its index
- [m, k] = max(A(:)); % max of whole matrix...
- [r, c] = ind2sub(size(A), k) % ...and its row/col
- B = A(A > 5) % logical indexing: pull values > 5
- A(A < 0) = 0 % replace all negatives with 0
- n = sum(x > 3) % COUNT how many satisfy condition
- any(x == 5), all(x > 0) % true/false checks
- SUBMATRIX
- S = A(1:2, 2:3) % rows 1-2, cols 2-3
- S = A([1 3], :) % rows 1 and 3, all columns
- S = A(:, [1 end]) % first and last columns
- S = A(2:end, 2:end) % drop first row and column
- evens = x(2:2:end) % every other element starting at 2
- rev = x(end:-1:1) % reverse a vector (or fliplr(x))
- ADDDELETE (adding / deleting elements)
- MATLAB Midterm Cheat Sheet
- Page 4 of 17
- x = [x 10] % append to end of row vector
- x = [0 x] % prepend
- A = [A; 10 11 12] % add a row at the bottom (must match # cols)
- A = [A, [1;2;3]] % add a column on the right (must match # rows)
- A(5,5) = 1 % assigning outside size auto-expands with zeros
- x(3) = [] % delete element 3
- A(2,:) = [] % delete row 2
- A(:,[1 3]) = [] % delete columns 1 and 3
- C = [A B] % side by side (same # rows)
- C = [A; B] % stacked (same # cols)
- REPMAT / reshape
- B = repmat(A, 2, 3) % tile A: 2 copies down, 3 across
- v = repmat([1 2], 1, 4) % [1 2 1 2 1 2 1 2]
- B = reshape(1:12, 3, 4) % 3x4 filled column by column
- B = reshape(A, 1, []) % flatten to a row ([] = figure it out)
- v = A(:) % flatten to a column
- B = reshape(A', 1, []) % flatten row by row
- B = fliplr(A), flipud(A), rot90(A)
- MATRIXFUNCS
- sum(x), prod(x), mean(x), median(x), std(x)
- sum(A) % sum of each COLUMN (row vector)
- sum(A,2) % sum of each ROW (column vector)
- sum(A(:)) % sum of everything
- cumsum(x) % running total
- max(A) % max of each column
- sort(x) % ascending
- [s, i] = sort(x,'descend') % descending + original positions
- sortrows(A, 2) % sort rows by column 2
- det(A), inv(A), rank(A), trace(A)
- unique(x), numel(unique(x))
- Plotting (data visualization)
- plot(x, y) needs x and y the same length. Always label axes and add a title; graders
- look for it.
- PLOTTING: full template
- MATLAB Midterm Cheat Sheet
- Page 5 of 17
- x = linspace(0, 2*pi, 100);
- y1 = sin(x);
- y2 = cos(x);
- figure; % new window
- plot(x, y1, 'b-', 'LineWidth', 2); % blue solid line
- hold on; % keep drawing on same axes
- plot(x, y2, 'r--o'); % red dashed with circles
- hold off;
- xlabel('x (rad)');
- ylabel('y');
- title('sin(x) and cos(x)');
- legend('sin', 'cos', 'Location', 'best');
- grid on;
- axis([0 2*pi -1.2 1.2]); % [xmin xmax ymin ymax]
- Shortcut for several curves in one line: plot(x, y1, 'b', x, y2, 'r') .
- Line style codes (combine them, e.g. 'r--o' )
- Subplots (several plots in one figure)
- subplot(2,1,1); plot(x, y1); title('top'); % 2 rows, 1 col, slot 1
- subplot(2,1,2); plot(x, y2); title('bottom'); % slot 2
- Other plot types
- Color Line Marker
- b blue, r red, g green, k black,
- m magenta, c cyan, y yellow
- - solid, -- dashed, :
- dotted, -. dash-dot
- o circle, * star, s square, x
- cross, . point, ^ triangle
- MATLAB Midterm Cheat Sheet
- Page 6 of 17
- fplot(@(x) exp(-0.2*x).*sin(6*x), [0 10]) % plot a function directly
- scatter(x, y) % dots only
- bar(y) % bar chart
- stem(y) % lollipop plot
- semilogy(x, y) % log y-axis
- loglog(x, y) % log both axes
- plot3(x, y, z) % 3D line
- [X,Y] = meshgrid(-2:0.1:2); Z = X.^2 + Y.^2;
- surf(X,Y,Z) % 3D surface; contour(X,Y,Z) for contours
- xlim([0 10]); ylim([-1 1]);
- text(1, 0.5, 'label here') % write text on the plot
- saveas(gcf, 'myplot.png') % save figure
- Loops, if/else, and playing music
- LOOPS
- % for loop: runs once per value
- for k = 1:5
- fprintf('k = %d\n', k);
- end
- % build a result inside a loop (preallocate first = faster)
- N = 10;
- y = zeros(1, N);
- for k = 1:N
- y(k) = k^2;
- end
- % loop over a matrix: nested loops
- for i = 1:size(A,1)
- for j = 1:size(A,2)
- A(i,j) = i + j;
- end
- end
- % running sum
- total = 0;
- for k = 1:100
- total = total + k;
- end
- MATLAB Midterm Cheat Sheet
- Page 7 of 17
- % while loop: runs until condition is false
- n = 0;
- while n^2 < 50
- n = n + 1;
- end
- % if / elseif / else
- if x > 0
- disp('positive');
- elseif x == 0
- disp('zero');
- else
- disp('negative');
- end
- Comparisons: == equal, ~= not equal, < , <= , > , >= . Logic: && and, || or, ~ not.
- break exits a loop early; continue skips to next iteration.
- MUSIC: playing notes with a for loop
- A note is a sine wave y = sin(2*pi*f*t) . Play it with sound(y, Fs) . Piano key number
- n (A4 = key 49) has frequency f = 440 * 2^((n-49)/12) . Each semitone up multiplies
- frequency by 2^(1/12).
- % ---- play one note ----
- Fs = 8192; % sampling rate (samples/s)
- dur = 0.5; % seconds
- t = 0:1/Fs:dur; % time vector
- f = 440; % A4
- y = sin(2*pi*f*t);
- sound(y, Fs);
- % ---- play a melody with a for loop ----
- Fs = 8192;
- keys = [40 40 47 47 49 49 47]; % Twinkle Twinkle (C C G G A A G)
- durs = [0.4 0.4 0.4 0.4 0.4 0.4 0.8]; % seconds per note
- song = []; % empty, we append to it
- Note (octave 4) C D E F G A B C5
- Key n 40 42 44 45 47 49 51 52
- Freq (Hz) 261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25
- MATLAB Midterm Cheat Sheet
- Page 8 of 17
- for k = 1:length(keys)
- f = 440 * 2^((keys(k)-49)/12); % key -> frequency
- t = 0:1/Fs:durs(k);
- note = sin(2*pi*f*t);
- song = [song note]; % append note
- end
- sound(song, Fs);
- % ---- same thing but with frequencies given directly ----
- freqs = [261.63 293.66 329.63 349.23 392.00];
- for k = 1:length(freqs)
- t = 0:1/Fs:0.3;
- sound(sin(2*pi*freqs(k)*t), Fs);
- pause(0.35); % wait so notes don't overlap
- end
- Rest (silence): zeros(1, round(Fs*dur)) . Chord: add sines then scale, y =
- (sin(2*pi*f1*t) + sin(2*pi*f2*t))/2 . Fade out to remove clicks: note = note .*
- linspace(1, 0, length(note)); . Save audio: audiowrite('song.wav', song, Fs) .
- Stop sound: clear sound .
- Custom functions: anonymous and M-file
- Two ways to write f(x) = e^(-0.2x) sin(6x). Use anonymous for one-line formulas; use an
- M-file when you need several lines, several outputs, or plots inside.
- ANONYMOUS (function handle, @ )
- f = @(x) exp(-0.2*x).*sin(6*x); % ALWAYS use .* ./ .^
- f(2) % evaluate at one point
- x = linspace(0, 10, 500);
- plot(x, f(x)); % evaluate on a vector
- g = @(x, y) x.^2 + y.^2; % two inputs
- g(3, 4) % -> 25
- a = 2;
- h = @(x) a*x.^2; % captures a's value NOW (later changes to
- a are ignored)
- fplot(f, [0 10]); % plot a handle directly
- MATLAB Midterm Cheat Sheet
- Page 9 of 17
- MFILE (function file)
- Rules: file name must equal function name ( h.m holds function ... = h(...) ). Save it
- in the Current Folder. Call it from the command window or a script.
- % ---- save as h.m ----
- function y = h(x)
- y = exp(-0.2*x).*sin(6*x);
- end
- % ---- multiple inputs and outputs: save as stats2.m ----
- function [avg, sd, biggest] = stats2(v)
- avg = mean(v);
- sd = std(v);
- biggest = max(v);
- end
- % call it:
- [a, s, b] = stats2([3 7 1 9])
- Functions inside a script: put them at the very BOTTOM of the script file, after all other
- code.
- FZERO and friends (using function handles)
- f = @(x) exp(-0.2*x).*sin(6*x);
- r = fzero(f, 0.5) % root nearest x = 0.5
- r = fzero(f, [0.4 0.6]) % root inside an interval (signs must
- differ)
- [xmin, fmin] = fminbnd(f, 0, 1) % minimum on [0,1]
- [xmax, negf] = fminbnd(@(x) -f(x), 0, 1); fmax = -negf % maximum
- I = integral(f, 0, 10) % definite integral
- p = polyfit(x, y, 2) % fit quadratic; polyval(p, x) to evaluate
- roots([1 -3 2]) % roots of x^2 - 3x + 2 -> 2, 1
- Basketball projectile M-file
- Inputs: shooter height h0 (m) and distance to hoop d (m). Hoop height is 3.05 m.
- "Optimum" angle = the angle needing the smallest launch speed. Example
- basketball(1.8, 7) gives about 50.06 degrees and 9.05 m/s.
- BASKETBALL: physics
- MATLAB Midterm Cheat Sheet
- Page 10 of 17
- With dy = hoop - h0 , the ball path is x = v cos(th) t , y = h0 + v sin(th) t - g
- t^2/2 . Forcing it through (d, hoop) gives the speed needed at each angle:
- v^2 = \frac{g\,d^2}{2\cos^2\theta\,(d\tan\theta - \Delta y)}, \qquad
- \theta_{opt} = 45^\circ + \tfrac{1}{2}\arctan\!\left(\frac{\Delta y}
- {d}\right)
- BASKETBALL: full function (save as basketball.m)
- function [theta_opt, v_opt] = basketball(h0, d)
- % BASKETBALL optimum launch angle + animated trajectory
- % h0 = release height (m), d = horizontal distance to hoop (m)
- g = 9.81; % m/s^2
- hoop = 3.05; % hoop height (m)
- dy = hoop - h0; % height the ball must rise
- % --- speed needed for every angle; pick the smallest ---
- theta = linspace(atand(dy/d) + 0.1, 89, 5000); % degrees
- v = sqrt( g*d^2 ./ (2*cosd(theta).^2 .* (d*tand(theta) - dy)) );
- [v_opt, i] = min(v);
- theta_opt = theta(i);
- theta_formula = 45 + 0.5*atand(dy/d); % analytic check
- fprintf('Optimum angle = %.2f deg (formula %.2f), speed = %.3f m/s\n',
- ...
- theta_opt, theta_formula, v_opt);
- % --- trajectory ---
- T = d / (v_opt*cosd(theta_opt)); % time to reach hoop
- t = linspace(0, T, 100);
- x = v_opt*cosd(theta_opt)*t;
- y = h0 + v_opt*sind(theta_opt)*t - 0.5*g*t.^2;
- % --- plot scene ---
- figure;
- plot(x, y, 'b--'); hold on;
- plot([0 0], [0 h0], 'b', 'LineWidth', 2); % shooter
- plot([d d+1.5], [hoop hoop], 'k', 'LineWidth', 2); %
- rim/backboard line
- plot(d, hoop, 'gs', 'MarkerFaceColor', 'g'); % hoop
- ball = plot(x(1), y(1), 'mo', 'MarkerSize', 10, 'MarkerFaceColor', 'm');
- axis([0 d+1.5 0 7]);
- xlabel('Distance (m)'); ylabel('Height (m)');
- title(sprintf('\\theta = %.1f^o, v = %.2f m/s', theta_opt, v_opt));
- MATLAB Midterm Cheat Sheet
- Page 11 of 17
- grid on;
- % --- animate ---
- for k = 1:length(t)
- set(ball, 'XData', x(k), 'YData', y(k));
- drawnow;
- pause(0.02);
- end
- hold off;
- end
- Run it: [th, v] = basketball(1.8, 7) .
- Variations they might ask
- % plot required speed vs angle (shows the minimum)
- plot(theta, v); xlabel('\theta (deg)'); ylabel('v (m/s)');
- % max height of the shot
- hmax = h0 + (v_opt*sind(theta_opt))^2/(2*g)
- % given a FIXED speed v0, find the angle that makes the shot
- miss = @(th) h0 + d*tand(th) - g*d^2./(2*v0^2*cosd(th).^2) - hoop;
- th = fzero(miss, 50)
- % save animation as a video
- vid = VideoWriter('shot.avi'); open(vid);
- % inside the for loop after drawnow: writeVideo(vid, getframe(gcf));
- close(vid);
- % simple animation alternative: redraw each frame
- for k = 1:length(t)
- plot(x(1:k), y(1:k), 'b', x(k), y(k), 'mo'); axis([0 9 0 7]);
- pause(0.02);
- end
- Linear equations: mesh analysis (A\b)
- Write each equation as (coefficients) x (unknowns) = (constant), stack coefficients into
- A and constants into b , then x = A\b . The lecture circuit gives I1 = 2.7987 A, I2 = 1.6981
- A, I3 = 2.4214 A.
- MATLAB Midterm Cheat Sheet
- Page 12 of 17
- MESH: lecture circuit (5V, 15V, resistors 1, 2, 3, 4, 5 ohm)
- % Loop 1: 5 = 1*I1 + 2*(I1 - I2) -> 3I1 - 2I2 = 5
- % Loop 2: 0 = 3*I2 + 2*(I2 - I1) + 4*(I2 - I3) -> -2I1 + 9I2 - 4I3 = 0
- % Loop 3: 15 = 5*I3 + 4*(I3 - I2) -> -4I2 + 9I3 = 15
- A = [ 3 -2 0;
- -2 9 -4;
- 0 -4 9];
- b = [5; 0; 15]; % COLUMN vector (semicolons!)
- I = A \ b % -> [2.7987; 1.6981; 2.4214]
- fprintf('I1 = %.4f A, I2 = %.4f A, I3 = %.4f A\n', I);
- check = A*I - b % should be ~0
- How to build A for any mesh circuit (shortcut)
- 1. Diagonal A(k,k) = sum of all resistors in loop k.
- 2. Off-diagonal A(j,k) = minus the resistor shared by loops j and k (0 if none).
- 3. b(k) = total source voltage in loop k (positive if it pushes current in the loop direction,
- negative if against).
- Other ways to solve (same answer)
- x = inv(A)*b % works, slower/less accurate than A\b
- x = linsolve(A, b)
- R = rref([A b]) % row-reduce augmented matrix; last column = answer
- det(A) % if 0 -> no unique solution
- rank(A) % must equal number of unknowns
- Generic word problem template
- % e.g. 2x + 3y - z = 5
- % 4x - y + 2z = 6
- % x + 2y + 3z = 14
- A = [2 3 -1; 4 -1 2; 1 2 3];
- b = [5; 6; 14];
- sol = A \ b;
- x = sol(1), y = sol(2), z = sol(3)
- Power in each resistor: P = I.^2 * R (current through a shared resistor = difference of
- the two loop currents, e.g. I1 - I2 ).
- MATLAB Midterm Cheat Sheet
- Page 13 of 17
- Eigenvalues and the quantum well
- [V, D] = eig(A) solves A v = lambda v. D is diagonal with eigenvalues; column k of V is
- the eigenvector for D(k,k) . MATLAB normalizes eigenvectors to length 1, so a sign flip
- versus your hand answer is still correct.
- EIGEN: basics
- A = [2 1; 1 2];
- lambda = eig(A) % just eigenvalues -> [1; 3]
- [V, D] = eig(A) % V = [-0.7071 0.7071; 0.7071 0.7071], D = diag([1
- 3])
- lam = diag(D) % eigenvalues as a vector
- v1 = V(:,1) % eigenvector for lam(1)
- % verify (each should be ~0)
- A*V - V*D
- A*V(:,1) - D(1,1)*V(:,1)
- % sort eigenvalues (and their vectors) smallest to largest
- [lam, idx] = sort(diag(D));
- V = V(:, idx);
- % characteristic polynomial det(A - lambda I) = 0
- p = poly(A) % coefficients
- roots(p) % same eigenvalues
- % scale eigenvector so first entry is 1 (to match hand answers)
- v1 / v1(1)
- QUANTUM: infinite square well with eig(H)
- Idea: chop the well into N points spaced dx. The second derivative becomes a tridiagonal
- matrix (-2 on the diagonal, 1 just above and below, divided by dx^2). Then H = -
- (hbar^2/2m) D2 + diag(V), and [psi, E] = eig(H) gives energies and wavefunctions.
- Exact answer for checking: E_n = n^2 pi^2 hbar^2 / (2 m L^2) = n^2 h^2 / (8 m L^2).
- \hat{H} = -\frac{\hbar^2}{2m}\frac{d^2}{dx^2} + V(x), \qquad \frac{d^2\psi}
- {dx^2} \approx \frac{\psi_{i+1} - 2\psi_i + \psi_{i-1}}{\Delta x^2}
- MATLAB Midterm Cheat Sheet
- Page 14 of 17
- % ---- natural units: hbar = 1, m = 1, L = 1 ----
- hbar = 1; m = 1; L = 1;
- N = 500; % interior grid points
- x = linspace(0, L, N+2); % include walls...
- x = x(2:end-1)'; % ...then drop them (psi = 0 there)
- dx = x(2) - x(1);
- e = ones(N,1);
- D2 = (diag(-2*e) + diag(e(1:N-1), 1) + diag(e(1:N-1), -1)) / dx^2;
- V = zeros(N,1); % infinite well: V = 0 inside
- H = -(hbar^2/(2*m))*D2 + diag(V);
- [psi, E] = eig(H);
- E = diag(E);
- [E, idx] = sort(E); psi = psi(:, idx); % lowest energy first
- psi = psi / sqrt(dx); % normalize: sum(psi.^2)*dx = 1
- n = (1:4)';
- E_exact = n.^2 * pi^2 * hbar^2 / (2*m*L^2);
- disp([n E(1:4) E_exact]) % numeric vs exact, should match
- fprintf('E2/E1 = %.3f (should be 4)\n', E(2)/E(1));
- % plot first 4 wavefunctions, each shifted up to its energy level
- figure; hold on;
- for k = 1:4
- plot(x, psi(:,k)*5 + E(k), 'LineWidth', 1.5); % *5 just to make it
- visible
- yline(E(k), ':');
- end
- xlabel('x'); ylabel('Energy / \psi'); title('Infinite square well');
- legend('n=1','','n=2','','n=3','','n=4',''); hold off;
- % probability density of ground state
- figure; plot(x, psi(:,1).^2); xlabel('x'); ylabel('|\psi_1|^2');
- QUANTUM: real units (electron in a 1 nm well, energies in eV)
- MATLAB Midterm Cheat Sheet
- Page 15 of 17
- hbar = 1.0546e-34; m = 9.109e-31; q = 1.602e-19; % J*s, kg, J per eV
- L = 1e-9; N = 500;
- x = linspace(0, L, N+2); x = x(2:end-1)'; dx = x(2) - x(1);
- e = ones(N,1);
- D2 = (diag(-2*e) + diag(e(1:N-1),1) + diag(e(1:N-1),-1)) / dx^2;
- H = -(hbar^2/(2*m))*D2; % + diag(V) if there is a potential
- (in J)
- E = sort(eig(H)) / q; % convert J -> eV
- E(1:3) % ~0.376, 1.504, 3.384 eV
- Other potentials (just change V , everything else is identical)
- V = 0.5 * (x - L/2).^2 * 1e4; % harmonic oscillator (spacing
- becomes even)
- V = 50 * (x > 0.4*L & x < 0.6*L); % barrier of height 50 in the middle
- V = 100 * (x < 0.3*L | x > 0.7*L); % finite well (inside 0.3L to 0.7L)
- V = 20 * x / L; % linear (tilted) potential
- Speed tip: for large N use sparse matrices, D2 = spdiags([e -2*e e], -1:1, N,
- N)/dx^2; then [psi,E] = eigs(H, 4, 'smallestreal'); .
- ERRORS: common messages and fixes
- Error / symptom Cause Fix
- Incorrect dimensions for
- matrix multiplication
- Used * on two vectors Use .* (also ./ , .^ )
- Arrays have incompatible
- sizes
- Adding/combining
- different-size arrays
- Check size() of both;
- transpose with '
- Vectors must be the same
- length (plot)
- x and y lengths differ Build y from the same x ;
- check length
- Index exceeds the number of
- array elements
- Asked for element past
- the end
- Check length / size ; loop to
- length(x) not a guessed
- number
- Array indices must be
- positive integers
- Index of 0 or a decimal MATLAB starts at 1; wrap in
- round()
- MATLAB Midterm Cheat Sheet
- Page 16 of 17
- Debugging tools: whos lists variables and sizes; size(x) before any operation; help
- name and doc name for syntax (both allowed in the exam).
- Error / symptom Cause Fix
- Dimensions of arrays being
- concatenated are not
- consistent
- [A; row] with wrong #
- columns
- New row must match
- size(A,2)
- Unrecognized function or
- variable
- Typo, or M-file not in
- Current Folder
- Check spelling; cd to the
- folder with the .m file
- Function name doesn't
- match file name
- h.m defines function y
- = g(x)
- Rename file or function so
- they match
- Not enough input arguments Pressed Run on a function
- file
- Call it from the command
- window with inputs: h(2)
- Matrix is singular / Inf / NaN
- in A\b
- Equations are dependent Recheck equations; det(A)
- should not be 0
- b wrong size in A\b b typed as a row Use semicolons: b = [5; 0;
- 15]
- sin of degrees gives weird
- values
- sin expects radians Use sind / cosd or deg2rad
- Plot overwrites previous plot No hold on Add hold on after first plot,
- or figure for a new window
- Animation doesn't move No screen refresh Add drawnow and
- pause(0.02) in the loop
- No sound Signal clipping or too short Keep values between -1 and 1;
- check Fs and duration
- MATLAB Midterm Cheat Sheet
- Page 17 of 17
|