uploaded all materials

This commit is contained in:
2025-03-24 00:43:09 -04:00
commit f2fb36f646
78 changed files with 15606 additions and 0 deletions

105
hw2/Ryan_hw2_013124.m Normal file
View File

@ -0,0 +1,105 @@
%%%% ECE210-B Matlab Seminar, Homework 2.
% james kit paul thomas ryan murphy, 1/31/24
% this is james' full name. -A.
% this should run in octave (7.3.0)!
close all; clear; clc;
%% Spatial Awareness
% (1)
A = reshape(0:63, 8, 8).';
B = 2 .^ A;
% (2)
B_colvec = reshape(B, [], 1);
% primes(64) = [2, 3, 5... 61]
% since we're asking for the prime indices from index 1 to index 64,
% getting all prime numbers within [0, 64] seems fitting
B_primeinds = B_colvec(primes(length(B_colvec)));
% (3)
B_primeinds_geometric_mean = prod(B_primeinds) .^ (1 / length(B_primeinds));
% (4)
% (1, :) -- Grab ALL of row 1 (aka the top row) in the matrix.
% fliplr -- flip left to right
A(1, :) = fliplr(A(1, :)); % :)
% (5)
% Keep all rows, keep all cols minus the end col
A_lastcol_del = A(1:8, 1:end-1);
%% Smallest Addition
% (1)
N = 100;
t = linspace(0, 6.66, N);
erf_integrand = exp(-t .^ 2);
figure;
title("Plot of e^{-t^2}, (100pts, [0, 6.66])");
xlabel("time");
ylabel("e^{-t^2}");
plot(t, erf_integrand);
% (2)
% derivative approximation,
% form some dt being the distance between points on our time axis
% form the derivative by dividing the formed erf_integrand over dt
dt = t(2) - t(1);
dfdt = diff(erf_integrand) ./ dt;
% padding op
dfdt = dfdt([1 1:end]);
% mean squared error between approximate taken and real erf deriv
dfdt_anal = -2 .* t .* exp( -t .^ 2);
msqerr_dfdt = (1 / N) .* mean((dfdt - dfdt_anal) .^ 2);
figure; hold on;
title('d/dt[e^{-t^2}] -- analytic vs approximate (100pts, [0, 6.66])');
xlabel('time');
ylabel('d/dt[-exp(t^2)]');
plot(t, dfdt, 'g-');
plot(t, dfdt_anal, 'r-');
% (3)
% integral approx
% take the area under the curve between t(n) and t(n-1)
% sum the area and scale by 2/sqrt(pi)
figure; hold on;
title('erf -- analytic vs approximate (100pts, [0, 6.66])');
xlabel('time');
ylabel('erf(t)');
% baseline
erf_anal = (sqrt(pi) ./ 2) .* erf(t);
% cum sum
erf_approx_cumsum = cumsum(erf_integrand) .* dt;
msqerr_erf_cumsum = (1 / N) .* mean((erf_approx_cumsum - erf_anal) .^ 2);
% cum trapz
erf_approx_cumtrapz = cumtrapz(erf_integrand) .* dt;
msqerr_erf_cumtrapz = (1 / N) .* mean((erf_approx_cumtrapz - erf_anal) .^ 2);
%{
The mean-square error of the cumsum op is 5 orders of magnitude larger
than the result from the cumtrapz op.
Qualitatively, the cumsum approximation (blue line) is noticably further
away than the cumtrapz approximation (red line). the cumsum also has
a non-negligible y intercept, which is much further than the cumtrapz
assumption. However, the cumtrapz is basically on top of the analytic
function (green line), which is especially novel considering both ops
used the same data set.
%}
% check
plot(t, erf_approx_cumsum, "b-");
plot(t, erf_approx_cumtrapz, "r-");
plot(t, erf_anal, "g-");

View File

@ -0,0 +1,117 @@
%%%% ECE210-B Matlab Seminar, Homework 2.
% james kit paul thomas ryan murphy, 1/31/24
% this is james' full name. -A.
% <+.01> i needed this.
% this should run in octave (7.3.0)!
% <3, turns out it also runs in MATLAB. love the comment,
% though.
close all; clear; clc;
%% Spatial Awareness
% (1)
A = reshape(0:63, 8, 8).';
B = 2 .^ A;
% (2)
B_colvec = reshape(B, [], 1);
% primes(64) = [2, 3, 5... 61]
% since we're asking for the prime indices from index 1 to index 64,
% getting all prime numbers within [0, 64] seems fitting
B_primeinds = B_colvec(primes(length(B_colvec)));
% very clean, like it.
% (3)
B_primeinds_geometric_mean = prod(B_primeinds) .^ (1 / length(B_primeinds));
% (4)
% (1, :) -- Grab ALL of row 1 (aka the top row) in the matrix.
% fliplr -- flip left to right
A(1, :) = fliplr(A(1, :)); % :)
% (5)
% Keep all rows, keep all cols minus the end col
A_lastcol_del = A(1:8, 1:end-1);
% that's one way! another is to assign to A (or a copy) with an
% empty matrix:
% A(:, end) = [];
%% Smallest Addition
% (1)
N = 100;
t = linspace(0, 6.66, N);
erf_integrand = exp(-t .^ 2);
figure;
title("Plot of e^{-t^2}, (100pts, [0, 6.66])");
xlabel("time");
ylabel("e^{-t^2}");
plot(t, erf_integrand);
% (2)
% derivative approximation,
% form some dt being the distance between points on our time axis
% form the derivative by dividing the formed erf_integrand over dt
dt = t(2) - t(1);
dfdt = diff(erf_integrand) ./ dt;
% padding op
dfdt = dfdt([1 1:end]);
% mean squared error between approximate taken and real erf deriv
dfdt_anal = -2 .* t .* exp( -t .^ 2);
msqerr_dfdt = (1 / N) .* mean((dfdt - dfdt_anal) .^ 2);
% <-.03> (repeated) this will underreport -- `mean()` already
% does a divide by the length of the array, so another divide
% by N is not necessary.
figure; hold on;
title('d/dt[e^{-t^2}] -- analytic vs approximate (100pts, [0, 6.66])');
xlabel('time');
ylabel('d/dt[-exp(t^2)]');
plot(t, dfdt, 'g-');
plot(t, dfdt_anal, 'r-');
% (3)
% integral approx
% take the area under the curve between t(n) and t(n-1)
% sum the area and scale by 2/sqrt(pi)
figure; hold on;
title('erf -- analytic vs approximate (100pts, [0, 6.66])');
xlabel('time');
ylabel('erf(t)');
% baseline
erf_anal = (sqrt(pi) ./ 2) .* erf(t);
% cum sum
erf_approx_cumsum = cumsum(erf_integrand) .* dt;
msqerr_erf_cumsum = (1 / N) .* mean((erf_approx_cumsum - erf_anal) .^ 2);
% cum trapz
erf_approx_cumtrapz = cumtrapz(erf_integrand) .* dt;
msqerr_erf_cumtrapz = (1 / N) .* mean((erf_approx_cumtrapz - erf_anal) .^ 2);
%{
The mean-square error of the cumsum op is 5 orders of magnitude larger
than the result from the cumtrapz op.
Qualitatively, the cumsum approximation (blue line) is noticably further
away than the cumtrapz approximation (red line). the cumsum also has
a non-negligible y intercept, which is much further than the cumtrapz
assumption. However, the cumtrapz is basically on top of the analytic
function (green line), which is especially novel considering both ops
used the same data set.
%}
% <+.02> love the explanatory comment. `cumtrapz` is
% surprisingly good at what it does!
% check
plot(t, erf_approx_cumsum, "b-");
plot(t, erf_approx_cumtrapz, "r-");
plot(t, erf_anal, "g-");

BIN
hw2/notes/lesson02.zip Normal file

Binary file not shown.

View File

@ -0,0 +1,75 @@
%% Lesson 2c: Numerical estimation of integrals and derivatives
% Numerical integration and differentiation are a staple of numerical
% computing. We will now see how easy these are in MATLAB!
clc; clear; close all;
%% The diff and cumsum functions
% Note the lengths of z, zdiff, and zcumsum! (Fencepost problem)
z = [0 5 -2 3 4];
zdiff = diff(z);
zcumsum = cumsum(z);
%% Setup: A simple function
% Let's start with a simple example: y = x.^2. The domain is N points
% linearly sampled from lo to hi.
lo = -2;
hi = 2;
N = 1e2;
x = linspace(lo, hi, N);
y = x.^2;
plot(x, y);
title('x^2');
%% Numerical (Approximate) Derivatives
% We can calculate a difference quotient between each pair of (x,y) points
% using the diff() function.
dydx = diff(y)./diff(x); % difference quotient
figure();
plot(x(1:end-1), dydx);
%% Numerical (Approximate) Integrals
% Now suppose we want to approximate the cumulative integral (Riemann sum)
% of a function.
xdiff = diff(x);
dx = xdiff(1); % spacing between points
dx = (hi-lo) / (N-1); % alternative to the above (note: N-1)
Y = cumsum(y) * dx; % Riemann sum
figure();
plot(x, Y);
%% Error metrics: Check how close we are!
% dydx should be derivative of x.^2 = 2*x
dydx_actual = 2 * x;
% Y should be \int_{-2}^{x}{t.^2 dt}
Y_actual = (x .^3 - (-2)^3) / 3;
% Slightly more accurate -- can you figure out why?
% Y_actual = (x .^3 - (-2-dx)^3) / 3;
% Error metric: MSE (mean square error) or RMSE (root mean square error)
% Try changing N and see how the error changes. Try this with both the
% integral and derivative.
% estimated = dydx;
% actual = dydx_actual(1:end-1);
estimated = Y;
actual = Y_actual;
mse = mean((estimated - actual) .^ 2);
rmse = rms(estimated - actual);
%% Fundamental Theorem of Calculus
% Now, use the approximate derivative to get the original function, y back
% as yhat and plot it. You may need to use/create another variable for
% the x axis when plotting.
figure();
yhat = diff(Y)./diff(x); % differentiate Y
plot(x(1:end-1), yhat);
figure();
yhat2 = cumsum(dydx) * dx; % integrate dydx
plot(x(1:end-1), yhat2);

1378
hw2/notes/octave-log.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,124 @@
%% Lesson 2a: More vector and matrix operations
%
% Objectives:
% * Understand how to perform vector operations in MATLAB
% * Understand arithmetic and basic functions in MATLAB
%% Vector operations
% In lesson 1, we saw how to create a vector with the colon operator and
% linspace. Now let's perform some operations on them!
%
% There are two common classes of operations that you can perform on vectors:
% element-wise operations (which produce another vector) and aggregate
% operations (which produce a scalar value). There are also many functions that
% don't fall under these categories, but these cover many of the common
% functions.
%% Element-wise operations
% Many operations that work on scalars (which are really degenerate matrices)
% also work element-wise on vectors (or matrices).
x = 0:0.01:2*pi; % Create a linearly-spaced vector
y = sin(x); % sin() works element-wise on vectors!
y = abs(x); % same with abs()!
y = x .^ 4; % element-wise power
y = power(x, 4); % same as above
plot(x, y); % Plot y vs. x (line graph)
title('y vs. x');
%% Aggregate operations
% Another common class of operations produce a single output or statistic about
% a vector (or matrix).
length(x); % number of elements in x
sum(x); % sum of the elements of x
mean(x); % average of the elements of x
min(x); % minimum element of x
diff(x); % difference between adjacent elements of x
%% Exercise 1 : Vector operations
T = 1e-6; % Sampling period (s)
t = 0:T:2e-3; % Time (domain/x-axis)
f0 = 50; % Initial frequency (Hz)
b = 10e6; % Chirp rate (Hz/s)
A = 10; % Amplitude
y1 = A * cos(2*pi*f0*t + pi*b*t.^2);
figure;
plot(t,y1);
%% Exercise: Numerical calculus
% See numerical_calculus.m.
%% Basic indexing in MATLAB
% The process of extracting values from a vector (or matrix) is called
% "indexing." In MATLAB, indices start at 1, rather than 0 in most languages
% (in which it is more of an "offset" than a cardinal index).
%% Exercise 2 : Basic indexing
% The syntax for indexing is "x(indices)", where x is the variable to index,
% and indices is a scalar or a vector of indices. There are many variations on
% this. Note that indices can be any vector
x(1); % first element of x
x(1:3); % elements 1, 2 and 3 (inclusive!)
x(1:length(x)); % all elements in x
x(1:end); % same as above
x(:); % same as above
x(end); % last element of x
x(3:end); % all elements from 3 onwards
x([1,3,5]); % elements 1, 3, and 5 from x
x(1:2:end); % all odd-indexed elements of x
ind = 1:2:length(x);
x(ind); % same as the previous example
%% Exercises to improve your understanding
% Take some time to go through these on your own.
x([1,2,3]); % Will these produce the same result?
x([3,2,1]);
x2 = 1:5;
x2(6); % What will this produce?
x2(0); % What will this produce?
x2(1:1.5:4); % What will this produce?
ind = 1:1.5:4;
x2(ind); % What will this produce?
z = 4;
z(1); % What will this produce?
%% Matrix operations
% Matrices is closely related to vectors, and we have also explored some matrix
% operations last class. This class, we are going to explore functions that are
% very useful but are hard to grasp for beginners, namely reshape, meshgrid,
% row-wise and column-wise operations.
%% Reshape
% Change a matrix from one shape to another. The new shape has to have the same
% number of elements as the original shape.
%
% When you are reshaping an array / matrix, the first dimension is filled
% first, and then the second dimension, so on and so forth. I.e., elements
% start filling down columns, then rows, etc.
M = 1:100;
N1 = reshape(M,2,2,[]); % It would create a 2*2*25 matrix
N2 = reshape(M,[2,2,25]); % Same as N1
N2(:,:,25); % Gives you 97,98,99,100
N2(:,1,25); % Gives you 97 and 98
%% Row-wise / Column-wise operations
% Vector operations can also be performed on matrices. We can perform a vector
% operation on each row/column of a matrix, or on a particular row/column by
% indexing.
H = magic(4); % create the magical matrix H
sum(H,1); % column wise sum, note that this is a row vector(default)
fliplr(H); % flip H from left to right
flipud(H); % flip H upside down
H(1,:) = fliplr(H(1,:)); % flip only ONE row left to right
H(1,:) = []; % delete the first row
%% Exercise 7 : Matrix Operations
H2 = randi(20,4,5); % random 4x5 matrix with integers from 1 to 20
sum(H2(:,2));
mean(H2(3,:));
C = reshape(H2,2,2,5);
C(2,:,:) = [];