test1_info.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. MATLAB Midterm Cheat Sheet
  2. Oct 10, 2026 · @Abhimanyu Varma
  3. Ctrl+F keyword index
  4. Search the keyword in the left column to jump to working code. Every code block runs as-
  5. is in MATLAB; change the numbers to match the exam question.
  6. If the question says... Ctrl+F this
  7. make a vector / range / evenly spaced points LINSPACE
  8. zeros, ones, identity, random matrix MAKEMATRIX
  9. size, number of elements SIZEOF
  10. multiply element by element, square each element DOTOPS
  11. get an element, row, column INDEXING
  12. find where a value is, max/min location FINDVALUE
  13. submatrix, extract block SUBMATRIX
  14. add a row/column, delete a row/column ADDDELETE
  15. repeat / tile a matrix, reshape REPMAT
  16. sort, sum, mean, transpose MATRIXFUNCS
  17. plot, labels, legend, multiple curves, subplot PLOTTING
  18. for loop, while loop, if/else LOOPS
  19. play a note, play music, sound, frequency MUSIC
  20. anonymous function, @(x) ANONYMOUS
  21. function file, M-file, multiple outputs MFILE
  22. find a root, minimum, integral of a function FZERO
  23. basketball, projectile, launch angle, animate BASKETBALL
  24. linear equations, Ax = b, circuit, Kirchhoff, mesh MESH
  25. MATLAB Midterm Cheat Sheet
  26. Page 1 of 17
  27. Basics: variables, vectors, matrices
  28. End a line with ; to hide output; leave it off to print the result. % starts a comment. clc
  29. clears the screen, clear clears variables, close all closes figures.
  30. LINSPACE / ranges
  31. x = 1:5 % [1 2 3 4 5]
  32. x = 0:0.5:2 % start:step:stop -> [0 0.5 1 1.5 2]
  33. x = 10:-2:0 % counting down -> [10 8 6 4 2 0]
  34. x = linspace(0, 2*pi, 20) % 20 evenly spaced points from 0 to 2pi
  35. r = [1 2 3] % row vector
  36. c = [1; 2; 3] % column vector (semicolons = new row)
  37. c = r' % transpose row -> column
  38. MAKEMATRIX
  39. A = [1 2 3; 4 5 6; 7 8 9] % 3x3, rows separated by ;
  40. Z = zeros(3,4) % 3 rows, 4 cols of 0
  41. O = ones(2,3) % all 1s
  42. I = eye(3) % 3x3 identity
  43. R = rand(3) % 3x3 random in (0,1)
  44. Ri = randi(10,3,3) % random integers 1..10, 3x3
  45. D = diag([1 2 3]) % diagonal matrix from a vector
  46. d = diag(A) % pull the diagonal out of a matrix
  47. M = magic(4) % handy test matrix
  48. SIZEOF
  49. If the question says... Ctrl+F this
  50. eigenvalues, eigenvectors, eig EIGEN
  51. quantum well, Schrodinger, Hamiltonian, energy
  52. levels
  53. QUANTUM
  54. error message ERRORS
  55. MATLAB Midterm Cheat Sheet
  56. Page 2 of 17
  57. [rows, cols] = size(A) % both dimensions
  58. size(A,1) % number of rows
  59. size(A,2) % number of columns
  60. length(x) % longest dimension (use for vectors)
  61. numel(A) % total number of elements
  62. DOTOPS (the most common exam mistake)
  63. A * B % matrix multiplication (inner dims must match)
  64. A .* B % element-by-element multiply (same size)
  65. A ./ B % element-by-element divide
  66. A .^ 2 % square every element
  67. A ^ 2 % A*A (matrix power, square matrices only)
  68. A' % transpose
  69. 2*A, A+3 % scalar ops work element-wise automatically
  70. Rule: if x is a vector and you write a formula in it, use .* , ./ , .^ everywhere. Example:
  71. y = exp(-0.2*x).*sin(6*x);
  72. Useful built-ins: sqrt , exp , log (natural), log10 , abs , sin/cos/tan (radians),
  73. sind/cosd/tand (degrees), asin/atan , atan2(y,x) , round , floor , ceil , mod(a,b) ,
  74. pi . Degrees to radians: deg2rad(d) , back: rad2deg(r) .
  75. Printing nicely
  76. disp(x) % print a value
  77. fprintf('I1 = %.4f A\n', I1) % 4 decimals, then newline
  78. fprintf('Angle = %.2f deg, v = %.3f m/s\n', th, v)
  79. format long % show more digits; format short to go back
  80. Manipulating matrices
  81. Indexing is always A(row, col) , starting at 1. : means "all", end means "last".
  82. INDEXING
  83. MATLAB Midterm Cheat Sheet
  84. Page 3 of 17
  85. A = [1 2 3; 4 5 6; 7 8 9];
  86. A(2,3) % row 2, col 3 -> 6
  87. A(2,:) % entire row 2 -> [4 5 6]
  88. A(:,1) % entire column 1 -> [1;4;7]
  89. A(end,end) % last element -> 9
  90. A(end,:) % last row
  91. A(5) % linear index: counts DOWN columns -> 5
  92. x(3) % 3rd element of a vector
  93. x(end-1) % second to last
  94. A(2,3) = 100 % change one element
  95. A(:,2) = 0 % set whole column 2 to zero
  96. FINDVALUE (locate a number)
  97. idx = find(x == 5) % positions where x equals 5
  98. idx = find(x > 3) % positions where condition true
  99. [r, c] = find(A == 6) % row and column of value 6 in matrix
  100. [r, c] = find(A > 5) % all rows/cols matching
  101. [m, i] = max(x) % max value and its index
  102. [m, i] = min(x) % min value and its index
  103. [m, k] = max(A(:)); % max of whole matrix...
  104. [r, c] = ind2sub(size(A), k) % ...and its row/col
  105. B = A(A > 5) % logical indexing: pull values > 5
  106. A(A < 0) = 0 % replace all negatives with 0
  107. n = sum(x > 3) % COUNT how many satisfy condition
  108. any(x == 5), all(x > 0) % true/false checks
  109. SUBMATRIX
  110. S = A(1:2, 2:3) % rows 1-2, cols 2-3
  111. S = A([1 3], :) % rows 1 and 3, all columns
  112. S = A(:, [1 end]) % first and last columns
  113. S = A(2:end, 2:end) % drop first row and column
  114. evens = x(2:2:end) % every other element starting at 2
  115. rev = x(end:-1:1) % reverse a vector (or fliplr(x))
  116. ADDDELETE (adding / deleting elements)
  117. MATLAB Midterm Cheat Sheet
  118. Page 4 of 17
  119. x = [x 10] % append to end of row vector
  120. x = [0 x] % prepend
  121. A = [A; 10 11 12] % add a row at the bottom (must match # cols)
  122. A = [A, [1;2;3]] % add a column on the right (must match # rows)
  123. A(5,5) = 1 % assigning outside size auto-expands with zeros
  124. x(3) = [] % delete element 3
  125. A(2,:) = [] % delete row 2
  126. A(:,[1 3]) = [] % delete columns 1 and 3
  127. C = [A B] % side by side (same # rows)
  128. C = [A; B] % stacked (same # cols)
  129. REPMAT / reshape
  130. B = repmat(A, 2, 3) % tile A: 2 copies down, 3 across
  131. v = repmat([1 2], 1, 4) % [1 2 1 2 1 2 1 2]
  132. B = reshape(1:12, 3, 4) % 3x4 filled column by column
  133. B = reshape(A, 1, []) % flatten to a row ([] = figure it out)
  134. v = A(:) % flatten to a column
  135. B = reshape(A', 1, []) % flatten row by row
  136. B = fliplr(A), flipud(A), rot90(A)
  137. MATRIXFUNCS
  138. sum(x), prod(x), mean(x), median(x), std(x)
  139. sum(A) % sum of each COLUMN (row vector)
  140. sum(A,2) % sum of each ROW (column vector)
  141. sum(A(:)) % sum of everything
  142. cumsum(x) % running total
  143. max(A) % max of each column
  144. sort(x) % ascending
  145. [s, i] = sort(x,'descend') % descending + original positions
  146. sortrows(A, 2) % sort rows by column 2
  147. det(A), inv(A), rank(A), trace(A)
  148. unique(x), numel(unique(x))
  149. Plotting (data visualization)
  150. plot(x, y) needs x and y the same length. Always label axes and add a title; graders
  151. look for it.
  152. PLOTTING: full template
  153. MATLAB Midterm Cheat Sheet
  154. Page 5 of 17
  155. x = linspace(0, 2*pi, 100);
  156. y1 = sin(x);
  157. y2 = cos(x);
  158. figure; % new window
  159. plot(x, y1, 'b-', 'LineWidth', 2); % blue solid line
  160. hold on; % keep drawing on same axes
  161. plot(x, y2, 'r--o'); % red dashed with circles
  162. hold off;
  163. xlabel('x (rad)');
  164. ylabel('y');
  165. title('sin(x) and cos(x)');
  166. legend('sin', 'cos', 'Location', 'best');
  167. grid on;
  168. axis([0 2*pi -1.2 1.2]); % [xmin xmax ymin ymax]
  169. Shortcut for several curves in one line: plot(x, y1, 'b', x, y2, 'r') .
  170. Line style codes (combine them, e.g. 'r--o' )
  171. Subplots (several plots in one figure)
  172. subplot(2,1,1); plot(x, y1); title('top'); % 2 rows, 1 col, slot 1
  173. subplot(2,1,2); plot(x, y2); title('bottom'); % slot 2
  174. Other plot types
  175. Color Line Marker
  176. b blue, r red, g green, k black,
  177. m magenta, c cyan, y yellow
  178. - solid, -- dashed, :
  179. dotted, -. dash-dot
  180. o circle, * star, s square, x
  181. cross, . point, ^ triangle
  182. MATLAB Midterm Cheat Sheet
  183. Page 6 of 17
  184. fplot(@(x) exp(-0.2*x).*sin(6*x), [0 10]) % plot a function directly
  185. scatter(x, y) % dots only
  186. bar(y) % bar chart
  187. stem(y) % lollipop plot
  188. semilogy(x, y) % log y-axis
  189. loglog(x, y) % log both axes
  190. plot3(x, y, z) % 3D line
  191. [X,Y] = meshgrid(-2:0.1:2); Z = X.^2 + Y.^2;
  192. surf(X,Y,Z) % 3D surface; contour(X,Y,Z) for contours
  193. xlim([0 10]); ylim([-1 1]);
  194. text(1, 0.5, 'label here') % write text on the plot
  195. saveas(gcf, 'myplot.png') % save figure
  196. Loops, if/else, and playing music
  197. LOOPS
  198. % for loop: runs once per value
  199. for k = 1:5
  200. fprintf('k = %d\n', k);
  201. end
  202. % build a result inside a loop (preallocate first = faster)
  203. N = 10;
  204. y = zeros(1, N);
  205. for k = 1:N
  206. y(k) = k^2;
  207. end
  208. % loop over a matrix: nested loops
  209. for i = 1:size(A,1)
  210. for j = 1:size(A,2)
  211. A(i,j) = i + j;
  212. end
  213. end
  214. % running sum
  215. total = 0;
  216. for k = 1:100
  217. total = total + k;
  218. end
  219. MATLAB Midterm Cheat Sheet
  220. Page 7 of 17
  221. % while loop: runs until condition is false
  222. n = 0;
  223. while n^2 < 50
  224. n = n + 1;
  225. end
  226. % if / elseif / else
  227. if x > 0
  228. disp('positive');
  229. elseif x == 0
  230. disp('zero');
  231. else
  232. disp('negative');
  233. end
  234. Comparisons: == equal, ~= not equal, < , <= , > , >= . Logic: && and, || or, ~ not.
  235. break exits a loop early; continue skips to next iteration.
  236. MUSIC: playing notes with a for loop
  237. A note is a sine wave y = sin(2*pi*f*t) . Play it with sound(y, Fs) . Piano key number
  238. n (A4 = key 49) has frequency f = 440 * 2^((n-49)/12) . Each semitone up multiplies
  239. frequency by 2^(1/12).
  240. % ---- play one note ----
  241. Fs = 8192; % sampling rate (samples/s)
  242. dur = 0.5; % seconds
  243. t = 0:1/Fs:dur; % time vector
  244. f = 440; % A4
  245. y = sin(2*pi*f*t);
  246. sound(y, Fs);
  247. % ---- play a melody with a for loop ----
  248. Fs = 8192;
  249. keys = [40 40 47 47 49 49 47]; % Twinkle Twinkle (C C G G A A G)
  250. durs = [0.4 0.4 0.4 0.4 0.4 0.4 0.8]; % seconds per note
  251. song = []; % empty, we append to it
  252. Note (octave 4) C D E F G A B C5
  253. Key n 40 42 44 45 47 49 51 52
  254. Freq (Hz) 261.63 293.66 329.63 349.23 392.00 440.00 493.88 523.25
  255. MATLAB Midterm Cheat Sheet
  256. Page 8 of 17
  257. for k = 1:length(keys)
  258. f = 440 * 2^((keys(k)-49)/12); % key -> frequency
  259. t = 0:1/Fs:durs(k);
  260. note = sin(2*pi*f*t);
  261. song = [song note]; % append note
  262. end
  263. sound(song, Fs);
  264. % ---- same thing but with frequencies given directly ----
  265. freqs = [261.63 293.66 329.63 349.23 392.00];
  266. for k = 1:length(freqs)
  267. t = 0:1/Fs:0.3;
  268. sound(sin(2*pi*freqs(k)*t), Fs);
  269. pause(0.35); % wait so notes don't overlap
  270. end
  271. Rest (silence): zeros(1, round(Fs*dur)) . Chord: add sines then scale, y =
  272. (sin(2*pi*f1*t) + sin(2*pi*f2*t))/2 . Fade out to remove clicks: note = note .*
  273. linspace(1, 0, length(note)); . Save audio: audiowrite('song.wav', song, Fs) .
  274. Stop sound: clear sound .
  275. Custom functions: anonymous and M-file
  276. Two ways to write f(x) = e^(-0.2x) sin(6x). Use anonymous for one-line formulas; use an
  277. M-file when you need several lines, several outputs, or plots inside.
  278. ANONYMOUS (function handle, @ )
  279. f = @(x) exp(-0.2*x).*sin(6*x); % ALWAYS use .* ./ .^
  280. f(2) % evaluate at one point
  281. x = linspace(0, 10, 500);
  282. plot(x, f(x)); % evaluate on a vector
  283. g = @(x, y) x.^2 + y.^2; % two inputs
  284. g(3, 4) % -> 25
  285. a = 2;
  286. h = @(x) a*x.^2; % captures a's value NOW (later changes to
  287. a are ignored)
  288. fplot(f, [0 10]); % plot a handle directly
  289. MATLAB Midterm Cheat Sheet
  290. Page 9 of 17
  291. MFILE (function file)
  292. Rules: file name must equal function name ( h.m holds function ... = h(...) ). Save it
  293. in the Current Folder. Call it from the command window or a script.
  294. % ---- save as h.m ----
  295. function y = h(x)
  296. y = exp(-0.2*x).*sin(6*x);
  297. end
  298. % ---- multiple inputs and outputs: save as stats2.m ----
  299. function [avg, sd, biggest] = stats2(v)
  300. avg = mean(v);
  301. sd = std(v);
  302. biggest = max(v);
  303. end
  304. % call it:
  305. [a, s, b] = stats2([3 7 1 9])
  306. Functions inside a script: put them at the very BOTTOM of the script file, after all other
  307. code.
  308. FZERO and friends (using function handles)
  309. f = @(x) exp(-0.2*x).*sin(6*x);
  310. r = fzero(f, 0.5) % root nearest x = 0.5
  311. r = fzero(f, [0.4 0.6]) % root inside an interval (signs must
  312. differ)
  313. [xmin, fmin] = fminbnd(f, 0, 1) % minimum on [0,1]
  314. [xmax, negf] = fminbnd(@(x) -f(x), 0, 1); fmax = -negf % maximum
  315. I = integral(f, 0, 10) % definite integral
  316. p = polyfit(x, y, 2) % fit quadratic; polyval(p, x) to evaluate
  317. roots([1 -3 2]) % roots of x^2 - 3x + 2 -> 2, 1
  318. Basketball projectile M-file
  319. Inputs: shooter height h0 (m) and distance to hoop d (m). Hoop height is 3.05 m.
  320. "Optimum" angle = the angle needing the smallest launch speed. Example
  321. basketball(1.8, 7) gives about 50.06 degrees and 9.05 m/s.
  322. BASKETBALL: physics
  323. MATLAB Midterm Cheat Sheet
  324. Page 10 of 17
  325. With dy = hoop - h0 , the ball path is x = v cos(th) t , y = h0 + v sin(th) t - g
  326. t^2/2 . Forcing it through (d, hoop) gives the speed needed at each angle:
  327. v^2 = \frac{g\,d^2}{2\cos^2\theta\,(d\tan\theta - \Delta y)}, \qquad
  328. \theta_{opt} = 45^\circ + \tfrac{1}{2}\arctan\!\left(\frac{\Delta y}
  329. {d}\right)
  330. BASKETBALL: full function (save as basketball.m)
  331. function [theta_opt, v_opt] = basketball(h0, d)
  332. % BASKETBALL optimum launch angle + animated trajectory
  333. % h0 = release height (m), d = horizontal distance to hoop (m)
  334. g = 9.81; % m/s^2
  335. hoop = 3.05; % hoop height (m)
  336. dy = hoop - h0; % height the ball must rise
  337. % --- speed needed for every angle; pick the smallest ---
  338. theta = linspace(atand(dy/d) + 0.1, 89, 5000); % degrees
  339. v = sqrt( g*d^2 ./ (2*cosd(theta).^2 .* (d*tand(theta) - dy)) );
  340. [v_opt, i] = min(v);
  341. theta_opt = theta(i);
  342. theta_formula = 45 + 0.5*atand(dy/d); % analytic check
  343. fprintf('Optimum angle = %.2f deg (formula %.2f), speed = %.3f m/s\n',
  344. ...
  345. theta_opt, theta_formula, v_opt);
  346. % --- trajectory ---
  347. T = d / (v_opt*cosd(theta_opt)); % time to reach hoop
  348. t = linspace(0, T, 100);
  349. x = v_opt*cosd(theta_opt)*t;
  350. y = h0 + v_opt*sind(theta_opt)*t - 0.5*g*t.^2;
  351. % --- plot scene ---
  352. figure;
  353. plot(x, y, 'b--'); hold on;
  354. plot([0 0], [0 h0], 'b', 'LineWidth', 2); % shooter
  355. plot([d d+1.5], [hoop hoop], 'k', 'LineWidth', 2); %
  356. rim/backboard line
  357. plot(d, hoop, 'gs', 'MarkerFaceColor', 'g'); % hoop
  358. ball = plot(x(1), y(1), 'mo', 'MarkerSize', 10, 'MarkerFaceColor', 'm');
  359. axis([0 d+1.5 0 7]);
  360. xlabel('Distance (m)'); ylabel('Height (m)');
  361. title(sprintf('\\theta = %.1f^o, v = %.2f m/s', theta_opt, v_opt));
  362. MATLAB Midterm Cheat Sheet
  363. Page 11 of 17
  364. grid on;
  365. % --- animate ---
  366. for k = 1:length(t)
  367. set(ball, 'XData', x(k), 'YData', y(k));
  368. drawnow;
  369. pause(0.02);
  370. end
  371. hold off;
  372. end
  373. Run it: [th, v] = basketball(1.8, 7) .
  374. Variations they might ask
  375. % plot required speed vs angle (shows the minimum)
  376. plot(theta, v); xlabel('\theta (deg)'); ylabel('v (m/s)');
  377. % max height of the shot
  378. hmax = h0 + (v_opt*sind(theta_opt))^2/(2*g)
  379. % given a FIXED speed v0, find the angle that makes the shot
  380. miss = @(th) h0 + d*tand(th) - g*d^2./(2*v0^2*cosd(th).^2) - hoop;
  381. th = fzero(miss, 50)
  382. % save animation as a video
  383. vid = VideoWriter('shot.avi'); open(vid);
  384. % inside the for loop after drawnow: writeVideo(vid, getframe(gcf));
  385. close(vid);
  386. % simple animation alternative: redraw each frame
  387. for k = 1:length(t)
  388. plot(x(1:k), y(1:k), 'b', x(k), y(k), 'mo'); axis([0 9 0 7]);
  389. pause(0.02);
  390. end
  391. Linear equations: mesh analysis (A\b)
  392. Write each equation as (coefficients) x (unknowns) = (constant), stack coefficients into
  393. A and constants into b , then x = A\b . The lecture circuit gives I1 = 2.7987 A, I2 = 1.6981
  394. A, I3 = 2.4214 A.
  395. MATLAB Midterm Cheat Sheet
  396. Page 12 of 17
  397. MESH: lecture circuit (5V, 15V, resistors 1, 2, 3, 4, 5 ohm)
  398. % Loop 1: 5 = 1*I1 + 2*(I1 - I2) -> 3I1 - 2I2 = 5
  399. % Loop 2: 0 = 3*I2 + 2*(I2 - I1) + 4*(I2 - I3) -> -2I1 + 9I2 - 4I3 = 0
  400. % Loop 3: 15 = 5*I3 + 4*(I3 - I2) -> -4I2 + 9I3 = 15
  401. A = [ 3 -2 0;
  402. -2 9 -4;
  403. 0 -4 9];
  404. b = [5; 0; 15]; % COLUMN vector (semicolons!)
  405. I = A \ b % -> [2.7987; 1.6981; 2.4214]
  406. fprintf('I1 = %.4f A, I2 = %.4f A, I3 = %.4f A\n', I);
  407. check = A*I - b % should be ~0
  408. How to build A for any mesh circuit (shortcut)
  409. 1. Diagonal A(k,k) = sum of all resistors in loop k.
  410. 2. Off-diagonal A(j,k) = minus the resistor shared by loops j and k (0 if none).
  411. 3. b(k) = total source voltage in loop k (positive if it pushes current in the loop direction,
  412. negative if against).
  413. Other ways to solve (same answer)
  414. x = inv(A)*b % works, slower/less accurate than A\b
  415. x = linsolve(A, b)
  416. R = rref([A b]) % row-reduce augmented matrix; last column = answer
  417. det(A) % if 0 -> no unique solution
  418. rank(A) % must equal number of unknowns
  419. Generic word problem template
  420. % e.g. 2x + 3y - z = 5
  421. % 4x - y + 2z = 6
  422. % x + 2y + 3z = 14
  423. A = [2 3 -1; 4 -1 2; 1 2 3];
  424. b = [5; 6; 14];
  425. sol = A \ b;
  426. x = sol(1), y = sol(2), z = sol(3)
  427. Power in each resistor: P = I.^2 * R (current through a shared resistor = difference of
  428. the two loop currents, e.g. I1 - I2 ).
  429. MATLAB Midterm Cheat Sheet
  430. Page 13 of 17
  431. Eigenvalues and the quantum well
  432. [V, D] = eig(A) solves A v = lambda v. D is diagonal with eigenvalues; column k of V is
  433. the eigenvector for D(k,k) . MATLAB normalizes eigenvectors to length 1, so a sign flip
  434. versus your hand answer is still correct.
  435. EIGEN: basics
  436. A = [2 1; 1 2];
  437. lambda = eig(A) % just eigenvalues -> [1; 3]
  438. [V, D] = eig(A) % V = [-0.7071 0.7071; 0.7071 0.7071], D = diag([1
  439. 3])
  440. lam = diag(D) % eigenvalues as a vector
  441. v1 = V(:,1) % eigenvector for lam(1)
  442. % verify (each should be ~0)
  443. A*V - V*D
  444. A*V(:,1) - D(1,1)*V(:,1)
  445. % sort eigenvalues (and their vectors) smallest to largest
  446. [lam, idx] = sort(diag(D));
  447. V = V(:, idx);
  448. % characteristic polynomial det(A - lambda I) = 0
  449. p = poly(A) % coefficients
  450. roots(p) % same eigenvalues
  451. % scale eigenvector so first entry is 1 (to match hand answers)
  452. v1 / v1(1)
  453. QUANTUM: infinite square well with eig(H)
  454. Idea: chop the well into N points spaced dx. The second derivative becomes a tridiagonal
  455. matrix (-2 on the diagonal, 1 just above and below, divided by dx^2). Then H = -
  456. (hbar^2/2m) D2 + diag(V), and [psi, E] = eig(H) gives energies and wavefunctions.
  457. Exact answer for checking: E_n = n^2 pi^2 hbar^2 / (2 m L^2) = n^2 h^2 / (8 m L^2).
  458. \hat{H} = -\frac{\hbar^2}{2m}\frac{d^2}{dx^2} + V(x), \qquad \frac{d^2\psi}
  459. {dx^2} \approx \frac{\psi_{i+1} - 2\psi_i + \psi_{i-1}}{\Delta x^2}
  460. MATLAB Midterm Cheat Sheet
  461. Page 14 of 17
  462. % ---- natural units: hbar = 1, m = 1, L = 1 ----
  463. hbar = 1; m = 1; L = 1;
  464. N = 500; % interior grid points
  465. x = linspace(0, L, N+2); % include walls...
  466. x = x(2:end-1)'; % ...then drop them (psi = 0 there)
  467. dx = x(2) - x(1);
  468. e = ones(N,1);
  469. D2 = (diag(-2*e) + diag(e(1:N-1), 1) + diag(e(1:N-1), -1)) / dx^2;
  470. V = zeros(N,1); % infinite well: V = 0 inside
  471. H = -(hbar^2/(2*m))*D2 + diag(V);
  472. [psi, E] = eig(H);
  473. E = diag(E);
  474. [E, idx] = sort(E); psi = psi(:, idx); % lowest energy first
  475. psi = psi / sqrt(dx); % normalize: sum(psi.^2)*dx = 1
  476. n = (1:4)';
  477. E_exact = n.^2 * pi^2 * hbar^2 / (2*m*L^2);
  478. disp([n E(1:4) E_exact]) % numeric vs exact, should match
  479. fprintf('E2/E1 = %.3f (should be 4)\n', E(2)/E(1));
  480. % plot first 4 wavefunctions, each shifted up to its energy level
  481. figure; hold on;
  482. for k = 1:4
  483. plot(x, psi(:,k)*5 + E(k), 'LineWidth', 1.5); % *5 just to make it
  484. visible
  485. yline(E(k), ':');
  486. end
  487. xlabel('x'); ylabel('Energy / \psi'); title('Infinite square well');
  488. legend('n=1','','n=2','','n=3','','n=4',''); hold off;
  489. % probability density of ground state
  490. figure; plot(x, psi(:,1).^2); xlabel('x'); ylabel('|\psi_1|^2');
  491. QUANTUM: real units (electron in a 1 nm well, energies in eV)
  492. MATLAB Midterm Cheat Sheet
  493. Page 15 of 17
  494. hbar = 1.0546e-34; m = 9.109e-31; q = 1.602e-19; % J*s, kg, J per eV
  495. L = 1e-9; N = 500;
  496. x = linspace(0, L, N+2); x = x(2:end-1)'; dx = x(2) - x(1);
  497. e = ones(N,1);
  498. D2 = (diag(-2*e) + diag(e(1:N-1),1) + diag(e(1:N-1),-1)) / dx^2;
  499. H = -(hbar^2/(2*m))*D2; % + diag(V) if there is a potential
  500. (in J)
  501. E = sort(eig(H)) / q; % convert J -> eV
  502. E(1:3) % ~0.376, 1.504, 3.384 eV
  503. Other potentials (just change V , everything else is identical)
  504. V = 0.5 * (x - L/2).^2 * 1e4; % harmonic oscillator (spacing
  505. becomes even)
  506. V = 50 * (x > 0.4*L & x < 0.6*L); % barrier of height 50 in the middle
  507. V = 100 * (x < 0.3*L | x > 0.7*L); % finite well (inside 0.3L to 0.7L)
  508. V = 20 * x / L; % linear (tilted) potential
  509. Speed tip: for large N use sparse matrices, D2 = spdiags([e -2*e e], -1:1, N,
  510. N)/dx^2; then [psi,E] = eigs(H, 4, 'smallestreal'); .
  511. ERRORS: common messages and fixes
  512. Error / symptom Cause Fix
  513. Incorrect dimensions for
  514. matrix multiplication
  515. Used * on two vectors Use .* (also ./ , .^ )
  516. Arrays have incompatible
  517. sizes
  518. Adding/combining
  519. different-size arrays
  520. Check size() of both;
  521. transpose with '
  522. Vectors must be the same
  523. length (plot)
  524. x and y lengths differ Build y from the same x ;
  525. check length
  526. Index exceeds the number of
  527. array elements
  528. Asked for element past
  529. the end
  530. Check length / size ; loop to
  531. length(x) not a guessed
  532. number
  533. Array indices must be
  534. positive integers
  535. Index of 0 or a decimal MATLAB starts at 1; wrap in
  536. round()
  537. MATLAB Midterm Cheat Sheet
  538. Page 16 of 17
  539. Debugging tools: whos lists variables and sizes; size(x) before any operation; help
  540. name and doc name for syntax (both allowed in the exam).
  541. Error / symptom Cause Fix
  542. Dimensions of arrays being
  543. concatenated are not
  544. consistent
  545. [A; row] with wrong #
  546. columns
  547. New row must match
  548. size(A,2)
  549. Unrecognized function or
  550. variable
  551. Typo, or M-file not in
  552. Current Folder
  553. Check spelling; cd to the
  554. folder with the .m file
  555. Function name doesn't
  556. match file name
  557. h.m defines function y
  558. = g(x)
  559. Rename file or function so
  560. they match
  561. Not enough input arguments Pressed Run on a function
  562. file
  563. Call it from the command
  564. window with inputs: h(2)
  565. Matrix is singular / Inf / NaN
  566. in A\b
  567. Equations are dependent Recheck equations; det(A)
  568. should not be 0
  569. b wrong size in A\b b typed as a row Use semicolons: b = [5; 0;
  570. 15]
  571. sin of degrees gives weird
  572. values
  573. sin expects radians Use sind / cosd or deg2rad
  574. Plot overwrites previous plot No hold on Add hold on after first plot,
  575. or figure for a new window
  576. Animation doesn't move No screen refresh Add drawnow and
  577. pause(0.02) in the loop
  578. No sound Signal clipping or too short Keep values between -1 and 1;
  579. check Fs and duration
  580. MATLAB Midterm Cheat Sheet
  581. Page 17 of 17