Преглед на файлове

Download classwork files

Pjotir преди 1 месец
родител
ревизия
e50833c431
променени са 54 файла, в които са добавени 919 реда и са изтрити 0 реда
  1. BIN
      classwork/Homework1/problem1_amplitude.mlx
  2. BIN
      classwork/Homework1/problem2_matrixstuff.mlx
  3. BIN
      classwork/Homework1/problem3_bigmatrixmanip.mlx
  4. BIN
      classwork/Homework1/problem4_plottingpractice.mlx
  5. 28 0
      classwork/Homework2/problem1_popgrowthplot.m
  6. 31 0
      classwork/Homework2/problem2_piformula.m
  7. 26 0
      classwork/Homework2/problem3_shortestpath.m
  8. 7 0
      classwork/Homework2/problem4_kitchoffslaw.m
  9. 29 0
      classwork/ODE_2ndOrder.m
  10. 24 0
      classwork/ODE_test.m
  11. BIN
      classwork/Sports.wav
  12. BIN
      classwork/UNCC_logo.jpg
  13. 24 0
      classwork/ball_traj_anim.m
  14. BIN
      classwork/ball_traj_anim_live.mlx
  15. 15 0
      classwork/basketball_test/InitialConditions.m
  16. 11 0
      classwork/basketball_test/ball_math.m
  17. BIN
      classwork/basketball_test/ball_math.mlx
  18. 19 0
      classwork/basketball_test/functions/animate_ball.m
  19. 7 0
      classwork/basketball_test/functions/calc_limits.m
  20. 9 0
      classwork/basketball_test/functions/projectile_motion.m
  21. 7 0
      classwork/basketball_test/functions/speed_for_angle.m
  22. 13 0
      classwork/basketball_test/functions/speed_for_angle_numerical.m
  23. 7 0
      classwork/calc_fibo.m
  24. 6 0
      classwork/e_approx.m
  25. BIN
      classwork/eigen_nonsense.mlx
  26. BIN
      classwork/eigen_nonsense2.mlx
  27. BIN
      classwork/eigen_nonsense3.mlx
  28. BIN
      classwork/eigen_nonsense4.mlx
  29. BIN
      classwork/flowers_red.jpg
  30. 7 0
      classwork/h.m
  31. 3 0
      classwork/input_test.m
  32. BIN
      classwork/linear_equations_test.mlx
  33. BIN
      classwork/markov_practice2.mlx
  34. BIN
      classwork/markov_practice3.mlx
  35. BIN
      classwork/markov_practive1.mlx
  36. 14 0
      classwork/octave_test.m
  37. 9 0
      classwork/pi_approx.m
  38. BIN
      classwork/piano_test.mlx
  39. 14 0
      classwork/quadratic_fit_test.m
  40. 4 0
      classwork/snells_law.m
  41. 5 0
      classwork/test.m
  42. 11 0
      classwork/test2.m
  43. BIN
      classwork/test_image.jpg
  44. BIN
      classwork/test_image_submatrix.jpg
  45. 8 0
      classwork/testf.m
  46. BIN
      classwork/untitled.mlx
  47. BIN
      classwork/untitled2.mlx
  48. BIN
      classwork/untitled3.mlx
  49. BIN
      classwork/untitled4.mlx
  50. BIN
      classwork/untitled5.mlx
  51. BIN
      classwork/untitled6.mlx
  52. BIN
      classwork/untitled7.mlx
  53. BIN
      classwork/untitled8.mlx
  54. 581 0
      test1_info.m

BIN
classwork/Homework1/problem1_amplitude.mlx


BIN
classwork/Homework1/problem2_matrixstuff.mlx


BIN
classwork/Homework1/problem3_bigmatrixmanip.mlx


BIN
classwork/Homework1/problem4_plottingpractice.mlx


Файловите разлики са ограничени, защото са твърде много
+ 28 - 0
classwork/Homework2/problem1_popgrowthplot.m


+ 31 - 0
classwork/Homework2/problem2_piformula.m

@@ -0,0 +1,31 @@
+fprintf("%.15f", approx_pi(1)) %[output:8ad5a476]
+fprintf("%.15f", approx_pi(3)) %[output:494950f9]
+fprintf("%.15f", approx_pi(5)) %[output:49f53ba2]
+fprintf("%.15f", approx_pi(10)) %[output:2fabe6fd]
+
+
+function r = approx_pi(steps)
+    total = 0;
+    for k = 0:steps
+        total = total + ((-1)^k) / ((2*k+1)*3^k);
+    end
+    r = 2 * sqrt(3) * total;
+end
+
+%[appendix]{"version":"1.0"}
+%---
+%[metadata:view]
+%   data: {"layout":"onright"}
+%---
+%[output:8ad5a476]
+%   data: {"dataType":"text","outputData":{"text":"3.079201435678004","truncated":false}}
+%---
+%[output:494950f9]
+%   data: {"dataType":"text","outputData":{"text":"3.137852891595680","truncated":false}}
+%---
+%[output:49f53ba2]
+%   data: {"dataType":"text","outputData":{"text":"3.141308785462883","truncated":false}}
+%---
+%[output:2fabe6fd]
+%   data: {"dataType":"text","outputData":{"text":"3.141593304503081","truncated":false}}
+%---

+ 26 - 0
classwork/Homework2/problem3_shortestpath.m

@@ -0,0 +1,26 @@
+% Constants for test
+a = 3; b = 5; d = 12; w = 1;
+
+% Testing all possible bridge positions (0 to d)
+[bridge_pos, path_distance] = fminbnd(@(x) calc_path(a,b,w,d,x), 0, d) %[output:32ce9065] %[output:590b847e]
+
+% a : vertical distance from town A to the river
+% b : vertical distance from town B to the river
+% w : width of the river
+% d : horizontal distance from town A to town B
+% x : horizontal distance of the bridge from town A
+function path_distance = calc_path(a, b, w, d, x)
+    path_distance = sqrt(x^2+a^2) + sqrt((d-x)^2+b^2) + w;
+end
+
+%[appendix]{"version":"1.0"}
+%---
+%[metadata:view]
+%   data: {"layout":"onright"}
+%---
+%[output:32ce9065]
+%   data: {"dataType":"textualVariable","outputData":{"name":"bridge_pos","value":"4.5000"}}
+%---
+%[output:590b847e]
+%   data: {"dataType":"textualVariable","outputData":{"name":"path_distance","value":"15.4222"}}
+%---

+ 7 - 0
classwork/Homework2/problem4_kitchoffslaw.m

@@ -0,0 +1,7 @@
+
+
+%[appendix]{"version":"1.0"}
+%---
+%[metadata:view]
+%   data: {"layout":"onright"}
+%---

Файловите разлики са ограничени, защото са твърде много
+ 29 - 0
classwork/ODE_2ndOrder.m


Файловите разлики са ограничени, защото са твърде много
+ 24 - 0
classwork/ODE_test.m


BIN
classwork/Sports.wav


BIN
classwork/UNCC_logo.jpg


+ 24 - 0
classwork/ball_traj_anim.m

@@ -0,0 +1,24 @@
+clear all;
+
+v_0 = 50;
+theta_0 = 45;
+h_0 = 0;
+g = 9.8;
+
+x = @(t) cosd(theta_0) .* v_0 .* t;
+y = @(t) h_0 + v_0 * sind(theta_0) .* t - (1/2) * g * t .^ 2;
+t = linspace(0, 10, 100); % Time vector from 0 to 10 seconds
+
+x_min = min(x(t)); y_min = min(y(t));
+x_max = max(x(t)); y_max = max(y(t));
+
+
+for t_current = t
+    plot(x(1:t_current), y(1:t_current));
+    hold on;
+    plot(x(t_current), y(t_current), 'ro', 'MarkerSize',25);
+    xlim([x_min x_max]);
+    ylim([y_min y_max]);
+    pause(0.05);
+    hold off;
+end

BIN
classwork/ball_traj_anim_live.mlx


+ 15 - 0
classwork/basketball_test/InitialConditions.m

@@ -0,0 +1,15 @@
+classdef InitialConditions < handle
+    properties
+        height_initial
+        height_final
+        displacement
+        theta_0
+        velocity
+        t_max
+        x_min
+        x_max
+        y_min
+        y_max
+        max_time
+    end
+end

+ 11 - 0
classwork/basketball_test/ball_math.m

@@ -0,0 +1,11 @@
+clear all;clc;close all;
+addpath('functions');
+
+p.height_initial = 1.8; 
+p.height_final = 3; 
+p.displacement = 7; 
+p.theta_0 = 45;
+
+[p.theta_0, p.velocity] = fminbnd(@(x) speed_for_angle(p, x), 0, 90);
+p = calc_limits(p);
+animate_ball(p);

BIN
classwork/basketball_test/ball_math.mlx


+ 19 - 0
classwork/basketball_test/functions/animate_ball.m

@@ -0,0 +1,19 @@
+function animate_ball(p)
+    time = linspace(0, p.t_max, 100);
+    [x_path, y_path] = projectile_motion(p, time);
+    for cur_time = 1:length(time)
+        hold on;
+
+        xlim([p.x_min-1 p.x_max+1]);
+        ylim([p.y_min p.y_max+1]);
+
+        plot([0,0], [0, p.height_initial], 'LineWidth',2, 'Color','blue');
+        plot(p.displacement, p.height_final, 'gs', 'MarkerSize',20);
+        plot([p.displacement, p.x_max], [p.height_final, p.height_final], 'LineWidth', 2, 'Color', 'green', 'LineStyle', '-');
+    
+        plot(x_path(1:cur_time), y_path(1:cur_time), 'Color', "red");
+        
+        pause(0.05);
+        hold off;
+    end
+end

+ 7 - 0
classwork/basketball_test/functions/calc_limits.m

@@ -0,0 +1,7 @@
+function p = calc_limits(p)
+    p.x_min = 0;
+    p.y_min = 0;
+    p.x_max = projectile_motion(p, p.t_max);
+    p.max_time = (p.velocity * sind(p.theta_0) / 9.8);
+    [dump, p.y_max] = projectile_motion(p, p.max_time);
+end

+ 9 - 0
classwork/basketball_test/functions/projectile_motion.m

@@ -0,0 +1,9 @@
+function [x, y] = projectile_motion(p, t)
+    g = 9.81;
+    theta_0 = p.theta_0;
+    velocity = p.velocity;
+    height_initial = p.height_initial;
+    
+    x = velocity * cosd(theta_0) * t.^2;
+    y = height_initial + velocity * sind(theta_0) * t - (1/2) * g * t.^2;
+end

+ 7 - 0
classwork/basketball_test/functions/speed_for_angle.m

@@ -0,0 +1,7 @@
+function initial_velocity = speed_for_angle(p, theta)
+    g = 9.81;
+    height_difference = p.height_final - p.height_initial;
+    top_term = g * p.displacement^2;
+    bottom_term = 2 * cosd(theta)^2 * (p.displacement * tand(theta) - height_difference);
+    initial_velocity = sqrt(top_term/bottom_term);
+end

+ 13 - 0
classwork/basketball_test/functions/speed_for_angle_numerical.m

@@ -0,0 +1,13 @@
+function initial_velocity = speed_for_angle_numerical(p, theta)
+    p.theta_0 = theta;
+    initial_velocity = fminbnd(@(v) trajectory_error(v), 0, 50);
+
+    function [error, t_max] = trajectory_error(v)
+        p.velocity = v;
+        time = linspace(0, 5, 2000);
+        [x_path, y_path] = projectile_motion(p, time);
+        distance = (x_path - p.displacement).^2 + (y_path-p.height_final).^2;
+        [error, index] = min(distance);
+        p.t_max = time(index);
+    end
+end

+ 7 - 0
classwork/calc_fibo.m

@@ -0,0 +1,7 @@
+function r = calc_fibo(n)
+    if n == 1 || n == 2
+        r = 1;
+    else
+        r = calc_fibo(n-1) + calc_fibo(n-2);
+    end
+end

+ 6 - 0
classwork/e_approx.m

@@ -0,0 +1,6 @@
+function r = e_approx(terms)
+    r = 0;
+    for n = 0:terms
+        r = r + (1/factorial(n));
+    end
+end

BIN
classwork/eigen_nonsense.mlx


BIN
classwork/eigen_nonsense2.mlx


BIN
classwork/eigen_nonsense3.mlx


BIN
classwork/eigen_nonsense4.mlx


BIN
classwork/flowers_red.jpg


+ 7 - 0
classwork/h.m

@@ -0,0 +1,7 @@
+function y = h(x)
+    y = x*6;
+    y = sin(y);
+    y = cos(y);
+    y = y.^3;
+    y = y .* exp(-0.2*x);
+end

+ 3 - 0
classwork/input_test.m

@@ -0,0 +1,3 @@
+keys = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
+selection = input("Enter key: ", 's');
+key = find(keys==selection)

BIN
classwork/linear_equations_test.mlx


BIN
classwork/markov_practice2.mlx


BIN
classwork/markov_practice3.mlx


BIN
classwork/markov_practive1.mlx


+ 14 - 0
classwork/octave_test.m

@@ -0,0 +1,14 @@
+function main()
+fprintf("%.15f\n", approx_pi(1));
+fprintf("%.15f\n", approx_pi(3));
+fprintf("%.15f\n", approx_pi(5));
+fprintf("%.15f\n", approx_pi(10));
+end
+
+function r = approx_pi(steps)
+total = 0;
+for k = 0:steps
+    total = total + ((-1)^k) / ((2*k+1)*3^k);
+end
+r = 2 * sqrt(3) * total;
+end

+ 9 - 0
classwork/pi_approx.m

@@ -0,0 +1,9 @@
+function sum = pi_approx(i)
+    sum = 0;
+    
+    for n = 0:i
+        sum = sum + ((-1)^n) / (2*n + 1);
+    end
+    
+    sum = sum * 4;
+end

BIN
classwork/piano_test.mlx


+ 14 - 0
classwork/quadratic_fit_test.m

@@ -0,0 +1,14 @@
+t = [0 1 2 3 4 5];
+x = [1.1 4.4 11.2 20.3 33.1 48.6];
+
+t = t';
+x = x';
+
+A = [t.^2 t ones(6,1)]
+p = A\x;
+t_fitted = linspace(min(t), max(t), 100);
+x_fitted = p(1)*t_fitted.^2 + p(2)*t_fitted + p(3);
+
+hold on;
+plot(t_fitted, x_fitted);
+plot(t, x, 'ro');

+ 4 - 0
classwork/snells_law.m

@@ -0,0 +1,4 @@
+function [refracted_angle, critical_angle] = snells_law(angle, n1, n2)
+    refracted_angle = asind((n1/n2)*sind(angle));
+    critical_angle = asind(n2/n1);
+end

+ 5 - 0
classwork/test.m

@@ -0,0 +1,5 @@
+u = 0; % initial velocity
+a = 3; % acceleration
+t = 10; % time
+v_final = u + a*t;
+x_final = (u*t) + (1/2)*a*t^2;

+ 11 - 0
classwork/test2.m

@@ -0,0 +1,11 @@
+u = 0; % initial velocity
+a = 3; % acceleration
+t = 10; % time
+v_final = u + a*t;
+x_final = (u*t) + (1/2)*a*t^2;
+
+%[appendix]{"version":"1.0"}
+%---
+%[metadata:view]
+%   data: {"layout":"onright"}
+%---

BIN
classwork/test_image.jpg


BIN
classwork/test_image_submatrix.jpg


+ 8 - 0
classwork/testf.m

@@ -0,0 +1,8 @@
+function r = testf(x)
+    x = 6 * x;
+    x = sin(x);
+    x = cos(x);
+    x = x .^ 3;
+    x = x * exp(-0.2 * x);
+    r = x;
+end

BIN
classwork/untitled.mlx


BIN
classwork/untitled2.mlx


BIN
classwork/untitled3.mlx


BIN
classwork/untitled4.mlx


BIN
classwork/untitled5.mlx


BIN
classwork/untitled6.mlx


BIN
classwork/untitled7.mlx


BIN
classwork/untitled8.mlx


+ 581 - 0
test1_info.m

@@ -0,0 +1,581 @@
+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

Някои файлове не бяха показани, защото твърде много файлове са промени