Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views16 pages

Results: Name: Alice BB, Mark: 3.5311E-41 Name: Bcharlie, Mark: Average Mark: 82.3333

Uploaded by

judahadetunji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

Results: Name: Alice BB, Mark: 3.5311E-41 Name: Bcharlie, Mark: Average Mark: 82.3333

Uploaded by

judahadetunji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

% Export to ASCII

save('exported_data.txt', 'time',
'measurement', '-ascii');
%% Experiment 1: Mathematical Functions
% Export to binary (.mat)
& Plotting
save('exported_data.mat', 'time',
x = -1:0.1:1;
'measurement');
% Plotting functions
figure;
%% Experiment 3: Low-Level File I/O
subplot(2,2,1);
% Writing student records to binary
plot(x, abs(x));
file
title('Absolute Value');
students = struct('Name', {'Alice',
xlabel('x');
'Bob', 'Charlie'}, 'Mark', {85, 72,
ylabel('abs(x)');
90});
grid on;
fid = fopen('student_records.bin',
subplot(2,2,2);
'w');
plot(x, acos(x));
for i = 1:length(students)
title('Arc Cosine');
fwrite(fid, students(i).Name,
xlabel('x');
'char');
ylabel('acos(x)');
fwrite(fid, students(i).Mark,
grid on;
'float');
subplot(2,2,3);
end
plot(x, asin(x));
fclose(fid);
title('Arc Sine');
% Reading and displaying records
xlabel('x');
fid = fopen('student_records.bin',
ylabel('asin(x)');
'r');
grid on;
while ~feof(fid)
subplot(2,2,4);
name = fread(fid, 10,
plot(x, atan(x));
'char=>char')'; % Transpose to make it
title('Arc Tangent');
a row vector
xlabel('x');
name = strtrim(name); % Remove
ylabel('atan(x)');
padding or trailing null characters
grid on;
if isempty(name) % Break if no
% Error handling for acos(x) outside [-
valid name is read
1,1]
break;
try
end
invalid_x = 2;
mark = fread(fid, 1, 'float');
acos(invalid_x);
disp(['Name: ', name, ', Mark: ',
catch ME
num2str(mark)]);
disp(['Error: ', ME.message]);
end
end
fclose(fid);
% Calculate average mark
%% Experiment 2: Data Import & Export
marks = [students.Mark];
% Example: Load CSV data (replace with
avg_mark = mean(marks);
actual file)
disp(['Average Mark: ',
data = readtable('experiment5.csv');
num2str(avg_mark)
time = data.Time;
measurement = data.Measurement;
% Plotting Results
figure;
plot(time, measurement); Name: Alice ªBB, Mark: 3.5311e-41
xlabel('Time'); Name: BCharlie , Mark:
ylabel('Measurement');
title('Time vs Measurement'); Average Mark: 82.3333
grid on;
(3000 + 0.5*(income - 20000)) .*
CHAPTER 6 (income > 20000);
disp('Tax:'); disp(tax);
%% Experiment 1: Logical Vectors &
Mathematical Applications
% Loan repayment
a = [1, 4, 7, 10, 12];
A = 10000; r = [0.05, 0.07]; n = 12; t =
disp('Elements > 5:'); disp(a(a > 5));
[5, 10];
disp('Elements divisible by 2:');
[R, T] = meshgrid(r, t);
disp(a(mod(a,2) == 0));
P = (A * (R./n) .* (1 + R./n).^(n.*T)) ./
disp('Count ≥ 5:'); disp(sum(a >= 5));
((1 + R./n).^(n.*T) - 1);
disp('Repayments:'); disp(P);
% Avoid division by zero
x = -pi:pi/20:pi;
% Random numbers
x(x == 0) = eps; % Replace 0 with epsilon
r = rand(1,10000);
y = sin(x) ./ x;
prop = sum(r < 0.5) / 10000;
figure; plot(x, y); title('sin(x)/x'); grid
disp('Proportion < 0.5:'); disp(prop);
on;
% Matrix filtering
% Discontinuous function
M = rand(10,10);
y = sin(x);
M(M < 0.2) = 0; M(M > 0.8) = 1;
y(y < 0) = 0;
figure; plot(x, y); title('Zeroed sin(x)');
%% Experiment 4: Matrix Operations
grid on;
A = [1,2,3; 4,5,6; 7,8,9];
disp('A(2,3):'); disp(A(2,3));
% Count random values
disp('Column 2:'); disp(A(:,2));
r = rand(1,1000);
disp('Count < 0.3:'); disp(sum(r < 0.3));
B = [9,8,7; 6,5,4; 3,2,1];
disp('Count ≥ 0.5:'); disp(sum(r >= 0.5));
C = A * B; D = A .* B;
disp('Matrix multiplication:'); disp(C);
%% Experiment 2: Advanced Logical Functions
disp('Element-wise multiplication:');
& Vectorization
disp(D);
b = rand(1,15);
disp('Any < 0.3:'); disp(any(b < 0.3));
disp('Transpose:'); disp(A');
disp('All > 0.5:'); disp(all(b > 0.5));
disp('Submatrix:'); disp(A(1:2,2:3));
% Dice simulation
% Reshaping
d = floor(6 * rand(1,1000)) + 1;
x = 1:9; X = reshape(x,3,3);
sixes = sum(d == 6);
disp('Reshaped matrix:'); disp(X);
disp('Empirical P(six):'); disp(sixes /
1000);
%% Experiment 5: Solving Linear Systems
% Linear system: 2x1 + 3x2 = 5; 4x1 + x2 =
% Monte Carlo π
6
points = rand(1000, 2);
A = [2,3; 4,1]; b = [5;6];
inside = sum(sqrt(points(:,1).^2 +
x = A \ b;
points(:,2).^2) <= 1);
disp('Solution:'); disp(x);
pi_est = 4 * inside / 1000;
disp('Estimated π:'); disp(pi_est);
% Determinant & inverse
A = [3,2; 4,1];
% Logical subsetting
disp('det(A):'); disp(det(A));
a = [-4, 0, 5, -3, 0, 3, 7, -1, 6];
disp('inv(A):'); disp(inv(A));
pos = a(a > 0); neg = a(a < 0); zero = a(a
== 0);
% Eigenvalues
A = [4,1; 2,3];
%% Experiment 3: Logical Vectors in Control
[V, D] = eig(A);
Structures
disp('Eigenvalues:'); disp(diag(D)');
% Tax calculation
income = [5000, 15000, 25000];
% LU decomposition
tax = income .* 0.1 .* (income <= 10000) +
A = [4,2; 3,1];
...
[L, U] = lu(A);
(1000 + 0.2*(income - 10000)) .*
disp('L:'); disp(L); disp('U:'); disp(U);
(income > 10000 & income <= 20000) + ...
%% Experiment 6: Multidimensional Arrays % Special matrices
% 3D array I = eye(3); P = pascal(5);
A = reshape(1:18, [3,2,3]); disp('Identity matrix:'); disp(I);
disp('3D slice:'); disp(A(:,:,3)); disp('Pascal matrix:'); disp(P);

% Reshaping % Tiling
B = 1:6; B_reshaped = reshape(B,2,3); row = [1,2,3]; tiled = repmat(row, 3, 1);
disp('Reshaped B:'); disp(B_reshaped); disp('Tiled matrix:'); disp(tiled);

>> chapter6 6 -0.2000 0.4000


0.8000 -0.6000
Elements > 5:
Column 2:
7 10 12
2 Eigenvalues:
5 5 2
Elements divisible by 2:
8
4 10 12
L:
Matrix multiplication: 1.0000 0
Count ≥ 5:
30 24 18 0.7500 1.0000
3
84 69 54
Count < 0.3: 138 114 90 U:
317 4.0000 2.0000
Element-wise multiplication: 0 -0.5000
Count ≥ 0.5: 9 16 21
488 24 25 24 3D slice:
21 16 9 13 16
Any < 0.3: 14 17
1 Transpose: 15 18
1 4 7
All > 0.5: 2 5 8 Reshaped B:
0 3 6 9 1 3 5
2 4 6
Empirical P(six): Submatrix:
0.1720 2 3 Identity matrix:
5 6 1 0 0
Estimated π: 0 1 0
3.0600 Reshaped matrix: 0 0 1
1 4 7
Tax: 2 5 8 Pascal matrix:
500 2000 5500 3 6 9 1 1 1 1 1
1 2 3 4 5
Repayments: Solution: 1 3 6 10 15
188.7123 198.0120 1.3000 1 4 10 20 35
106.0655 116.1085 0.8000 1 5 15 35 70

Proportion < 0.5: det(A): Tiled matrix:


0.4997 -5 1 2 3
1 2 3
A(2,3): inv(A): 1 2 3
CHAPTER 7 plot(x, f(x), 'm-', 'LineWidth', 2);
title('f(x) = e^{sin(x)} - 1 + cos(x) +
%% Experiment 1: Advanced 2D Plotting log(x^2+1)sin(x)');
x = linspace(-10, 10, 1000); xlabel('x'); ylabel('f(x)'); grid on;
f = @(x) sin(x).*cos(x) + 2*atan(x); hold on;

figure; % Plot components


plot(x, f(x), 'r--', 'LineWidth', 1.5); plot(x, exp(sin(x)) - 1, 'c--');
title('Plot of f(x) = sin(x)cos(x) + plot(x, cos(x), 'k:');
2tan^{-1}(x)'); plot(x, log(x.^2 + 1).*sin(x), 'y-.');
xlabel('x values'); ylabel('f(x) legend('Composite', 'e^{sin(x)} - 1',
Values'); 'cos(x)', 'log(x^2+1)sin(x)');
grid on; hold on;
axis equal;
% Plot components saveas(gcf, 'Complex_2D_Plot.tiff');
plot(x, sin(x).*cos(x), 'b-o',
'MarkerIndices', 1:100:length(x)); %% Experiment 3: 3D Plotting
plot(x, 2*atan(x), 'g--s', [X, Y] = meshgrid(linspace(-5, 5, 50));
'MarkerIndices', 1:100:length(x)); Z = sin(X.^2 + Y.^2) .* exp(-X.^2/10)
legend('Composite', 'sin(x)cos(x)', .* tan(X.*Y) .* ...
'2tan^{-1}(x)'); log(X + Y + 1) ./ (X.^2 + Y.^2 +
3);
% Annotate extrema
[~, max_idx] = max(f(x)); % Ensure Z is real
text(x(max_idx), f(x(max_idx)), 'Local Z = real(Z);
Max', 'VerticalAlignment', 'bottom');
% Surface plot
axis([-10 10 -1.5 2.5]); figure;
saveas(gcf, '2D_Plot.png'); subplot(1, 2, 1);
surf(X, Y, Z, 'EdgeColor', 'none');
%% Experiment 2: Complex 2D Functions title('3D Surface Plot');
[X, Y] = meshgrid(linspace(-10, 10, xlabel('x'); ylabel('y');
100), linspace(-10, 10, 100)); zlabel('f(x,y)');
Z = exp(sin(X)) - 1 + cos(Y) + log(X.^2
+ Y.^2 + 1).*sin(Y); % Contour plot
subplot(1, 2, 2);
% Ensure Z is real contour(X, Y, Z, 20, 'LineWidth', 1.5);
Z = real(Z); title('Contour Plot'); xlabel('x');
ylabel('y');
figure; colorbar;
surf(X, Y, Z, 'EdgeColor', 'none');
title('Surface Plot of Complex % Animation
Function'); figure;
xlabel('X'); ylabel('Y'); zlabel('Z'); for angle = 0:5:360
colorbar; surf(X, Y, Z); view(angle, 30);
title(sprintf('Rotation: %d°',
f = @(x) exp(sin(x)) - 1 + cos(x) + angle));
log(x.^2 + 1).*sin(x); drawnow;
end
figure; saveas(gcf, '3D_Surface.png');
CHAPTER 8 u = 60; g = 9.8; t = 0; dt = 0.1;
x = 0; y = 0; trajectory = [x, y];
%% Experiment 1: Binomial Coefficient while y >= 0
(for Loop) t = t + dt;
n = input('Enter n: '); x = u * cos(theta) * t;
r = input('Enter r: '); y = u * sin(theta) * t - 0.5 * g *
numerator = 1; t^2;
for k = 0:r-1 if y >= 0
numerator = numerator * (n - k); trajectory = [trajectory; x,
end y];
denominator = factorial(r); end
C = numerator / denominator; end
fprintf('C(%d, %d) = %d\n', n, r, C); % Create a new figure for Experiment 3
% Create a new figure for Experiment 1 figure;
(optional visualization) plot(trajectory(:,1), trajectory(:,2),
figure; 'r-', 'LineWidth', 1.5);
bar(0:r-1, numerator ./ factorial(0:r- xlabel('Horizontal Distance (m)');
1)); ylabel('Vertical Distance (m)');
xlabel('k'); ylabel('Value'); title('Experiment 3: Projectile
title('Binomial Coefficient Motion');
Visualization'); grid on;
grid on; % Optimization for maximum range
%% Experiment 2: Temperature Modeling angles = 0:1:90;
(while Loop) ranges = zeros(size(angles));
T = 25; F = 10; K = input('Enter for i = 1:length(angles)
cooling constant K: '); theta = angles(i) * pi / 180;
dt = input('Enter time step dt: '); t = 0; y = 0;
opint = input('Enter output interval while y >= 0
opint: '); y = u * sin(theta) * t - 0.5 *
if mod(opint, dt) ~= 0 g * t^2;
error('opint must be an integer t = t + dt;
multiple of dt.'); end
end ranges(i) = u * cos(theta) * (t -
time = 0; results = [time, T]; dt);
while T > F + 0.01 end
T = T - K * dt * (T - F); [~, idx] = max(ranges);
time = time + dt; fprintf('Optimal angle: %d°\n',
if mod(time, opint) == 0 angles(idx));
results = [results; time, T]; % Create a new figure for range
end optimization
end figure;
% Create a new figure for Experiment 2 plot(angles, ranges, 'g-', 'LineWidth',
figure; 1.5);
plot(results(:,1), results(:,2), 'b-', xlabel('Launch Angle (°)');
'LineWidth', 1.5); ylabel('Range (m)');
xlabel('Time (s)'); ylabel('Temperature title('Experiment 3: Range vs Launch
(°C)'); Angle');
title('Experiment 2: Temperature grid on;
Modeling'); %% Experiment 4: π Approximation (for
grid on; Loop)
%% Experiment 3: Projectile Motion n = input('Enter number of terms: ');
(while Loop) pi_approx = 0;
theta = input('Enter launch angle for k = 0:n-1
(deg): ') * pi / 180; pi_approx = pi_approx + (-1)^k /
(2*k + 1);
end pi_terms = arrayfun(@(k) 4 * sum((-
pi_approx = 4 * pi_approx; 1).^(0:k) ./ (2*(0:k) + 1)), k_values);
fprintf('Approximated π: %.6f (Error: plot(k_values, pi_terms, 'm-',
%.6f)\n', pi_approx, abs(pi - 'LineWidth', 1.5);
pi_approx)); xlabel('Number of Terms');
% Create a new figure for π ylabel('Approximated π');
approximation title('Experiment 4: π Approximation
figure; Convergence');
k_values = 0:n-1; grid on;

>> chapter8 Enter output interval opint: 16


Enter n: 5 Enter launch angle (deg): 45
Enter r: 3 Optimal angle: 44°
C(5, 3) = 10 Enter number of terms: 4
Enter cooling constant K: 0.1 Approximated π: 2.895238 (Error: 0.246355)
Enter time step dt: 4 >>
figure;
CHAPTER 9 bar(x);
xlabel('Variable Index'); ylabel('Value');
%% Experiment 1 Solutions title('Task 2: Ill-conditioned System');
% Task 1: Fixed Syntax Errors grid on;
x = 5; %% Experiment 3 Solutions
y = 3; % Task 1: Division with Try-Catch
result = x * (y + 2); % Added missing num1 = 10;
operator and parenthesis num2 = 0;
disp(['The result is ', num2str(result)]); try
% Fixed string concatenation result = num1 / num2;
% Task 2: Corrected Derivative Calculation catch ME
x = 2; disp('Error occurred: Division by
h = 1; zero!');
f = @(x) x^2; % Proper function handle disp(ME.message);
derivative = (f(x+h) - f(x)) / h; % Correct end
Newton quotient % Task 2: Quadratic Solver
disp(['Approximate derivative: ', a = input('Enter coefficient a (non-zero):
num2str(derivative)]); ');
% Task 3: Vector Length Matching b = input('Enter coefficient b: ');
x = 0:pi/20:3*pi; c = input('Enter coefficient c: ');
y = sin(x); if a == 0
% Ensure matching lengths: disp('This is not a quadratic equation!
x = 0:pi/20:3*pi; % Consistent definition Please enter a non-zero value for a.');
% Create a new figure for Task 3 else
figure; discriminant = b^2 - 4*a*c;
plot(x, y); if discriminant < 0
xlabel('x'); ylabel('sin(x)'); disp('The equation has complex
title('Task 3: Vector Length Matching'); roots.');
grid on; root1 = (-b +
%% Experiment 2 Solutions sqrt(discriminant))/(2*a);
% Task 1: Rounding Error Demonstration root2 = (-b -
x = 2; sqrt(discriminant))/(2*a);
f = @(x) x^2; fprintf('Roots: %.2f + %.2fi and
h = 1; %.2f - %.2fi\n', real(root1), imag(root1),
figure; % Create a new figure for Task 1 real(root2), imag(root2));
hold on; else
for i = 1:16 root1 = (-b +
derivative = (f(x+h) - f(x)) / h; sqrt(discriminant))/(2*a);
fprintf('h = %e, Derivative = %.15f\n', root2 = (-b -
h, derivative); sqrt(discriminant))/(2*a);
h = h/10; fprintf('Roots: %.2f and %.2f\n',
end root1, root2);
hold off; end
% Task 2: Ill-conditioned System end
A = [0.2038 0.1218; 0.4071 0.2436]; % Task 3: Multiple Error Analysis
b = [0.2014; 0.4038]; % Original error-generating code:
cond(A) % Shows ill-conditioning (cond ≈ % x = 5; y = 'hello'; z = x + y; % Fixed by
1.6e+16) using consistent types
x = A\b; % MATLAB's solution % a = sin(); % Fixed by adding argument:
fprintf('Solution: x = %.2f, y = %.2f\n', sin(pi/2)
x(1), x(2)); % b = [1, 2; 3, 4]; c = b + [1,2,3]; %
% Create a new figure for Task 2 Fixed by matching dimensions

>> chapter9 5.000000000000000 4.009999999999891


The result is 25 h = 1.000000e-01, Derivative = h = 1.000000e-03, Derivative =
Approximate derivative: 5 4.100000000000001 4.000999999999699
h = 1.000000e+00, Derivative = h = 1.000000e-02, Derivative = h = 1.000000e-04, Derivative =
4.000100000007834 4.000000330961483
h = 1.000000e-05, Derivative = h = 1.000000e-11, Derivative = 4.6214e+03
4.000010000027032 4.000000330961483 Solution: x = -2.00, y = 5.00
h = 1.000000e-06, Derivative = h = 1.000000e-12, Derivative = Enter coefficient a (non-zero): 8
4.000001000648012 4.000355602329363 Enter coefficient b: 4
h = 1.000000e-07, Derivative = h = 1.000000e-13, Derivative = Enter coefficient c: 3
4.000000091153310 3.996802888650563 The equation has complex
h = 1.000000e-08, Derivative = h = 1.000000e-14, Derivative = roots.
3.999999975690115 4.085620730620575 Roots: -0.25 + 0.56i and -0.25 - -
h = 1.000000e-09, Derivative = h = 1.000000e-15, Derivative = 0.56i
4.000000330961483 3.552713678800500
>>
h = 1.000000e-10, Derivative = ans =
% Normal CDF approximation
CHAPTER 10 x = 0:0.1:4;
approx = arrayfun(@normal_cdf, x);
%% Experiment 1 Solutions exact = normcdf(x);
max_error = max(abs(approx - exact));
% Inline function for coupled oscillators fprintf('Maximum error: %.2e\n', max_error);
h = @(t) cos(8*t) + cos(9*t);
t = 0:pi/40:6*pi; % Plot comparison
figure; figure;
plot(t, h(t)); plot(x, approx, 'r-', x, exact, 'b--');
title('Coupled Harmonic Oscillators'); legend('Approximation', 'Exact');
xlabel('Time (t)'); ylabel('Amplitude'); title('Normal CDF Approximation vs Exact');
xlabel('x'); ylabel('CDF');
% Extended system grid on;
h4 = @(t) cos(8*t) + cos(9*t) + cos(10*t) +
cos(11*t); %% Function Definitions
figure;
plot(t, h4(t)); % Function for f(x)
title('Four Coupled Oscillators'); function y = f(x)
xlabel('Time (t)'); ylabel('Amplitude'); y = x^3 + x - 3;
end
%% Experiment 2 Solutions
% Function for f'(x)
% Newton's method implementation function y = fprime(x)
x0 = 1; tol = 1e-5; maxiter = 100; y = 3*x^2 + 1;
for iter = 1:maxiter end
x1 = x0 - f(x0)/fprime(x0);
if abs(x1 - x0)/abs(x1) < tol % Recursive factorial function
break; function result = fact(n)
end fprintf('n = %d\n', n);
x0 = x1; if n <= 1
end result = 1;
fprintf('Root: %.6f in %d iterations\n', x1, else
iter); result = n * fact(n-1);
end
%% Experiment 3 Solutions end

% Recursive factorial function % Generalized Newton's method


for k = 1:10 function root = newtgen_general(f, fprime, x0,
fprintf('%d! = %d\n', k, fact(k)); tol)
end maxiter = 100;
for iter = 1:maxiter
%% Experiment 4 Solutions x1 = x0 - f(x0)/fprime(x0);
if abs(x1 - x0)/abs(x1) < tol
% Debugging newtgen_general root = x1;
% Set breakpoints at: return;
% 1. Function entry end
% 2. Inside iteration loop x0 = x1;
% 3. Termination condition end
dbstop in newtgen_general at 10; % Set breakpoint warning('Max iterations reached');
at line 10 end
newtgen_general(@f, @fprime, 1.0, 1e-5);
% Normal CDF approximation
%% Experiment 5 Solutions function p = normal_cdf(x)
b = 0.2316419;
% Function handle version a = 0.319381530;
f1 = @(x) x^2 - 2; c = -0.356563782;
f1prime = @(x) 2*x; d = 1.781477937;
root = newtgen_general(f1, f1prime, 1.0, 1e-5); t = 1./(1 + b*x);
fprintf('Root of f1: %.6f\n', root); phi = exp(-x.^2/2)/sqrt(2*pi);
p = 0.5 - phi.*(a*t + c*t.^3 + d*t.^5);
%% Experiment 6 Solutions end

>> chapter10 n=1 n=1 n=2


Root: 1.213412 in 4 1! = 1 2! = 2 n=1
iterations n=2 n=3 3! = 6
n=4 n=1 n=2 n=7
n=3 6! = 720 n=1 n=6
n=2 n=7 8! = 40320 n=5
n=1 n=6 n=9 n=4
4! = 24 n=5 n=8 n=3
n=5 n=4 n=7 n=2
n=4 n=3 n=6 n=1
n=3 n=2 n=5 10! = 3628800
n=2 n=1 n=4 Root of f1: 1.414214
n=1 7! = 5040 n=3 Maximum error: 6.96e-
5! = 120 n=8 n=2 01
n=6 n=7 n=1
>>
n=5 n=6 9! = 362880
n=4 n=5 n = 10
n=3 n=4 n=9
n=2 n=3 n=8
% 20-bin histogram
CHAPTER 11 figure;
histogram(scores, 20);
%% Cooling Model with Variable Time Steps
title('Test Scores: 20 Bins');
K = 0.1; F = 10; T0 = 25;
xlabel('Score');
dt = input('Enter time step: ');
ylabel('Frequency');
t_total = 100; % minutes
grid on;
steps = ceil(t_total/dt);
% Frequency table
% Pre-allocation
bin_edges = 40:10:100;
T = zeros(1, steps+1);
[N, ~] = histcounts(scores, bin_edges);
T(1) = T0;
fprintf('Score Range\tCount\n');
for i = 1:steps
for i = 1:length(N)
T(i+1) = T(i) - K*dt*(T(i) - F);
fprintf('%d-%d\t\t%d\n', bin_edges(i),
end
bin_edges(i+1), N(i));
% Exact solution
end
t_exact = 0:0.1:t_total;
%% Bubble Sort Implementation
T_exact = F + (T0 - F)*exp(-K*t_exact);
data = randi([1 100], 1, 50); % Random
% Plot comparison
dataset
figure;
n = length(data);
plot(0:dt:t_total, T, 'r-', t_exact,
sorted = data;
T_exact, 'b--');
tic;
legend('Numerical', 'Exact');
for i = 1:n-1
title('Cooling Model with Variable Time
for j = 1:n-i
Steps');
if sorted(j) > sorted(j+1)
xlabel('Time (minutes)');
% Swap
ylabel('Temperature (°C)');
temp = sorted(j);
grid on;
sorted(j) = sorted(j+1);
%% 1D Random Walk Simulation
sorted(j+1) = temp;
n_steps = 1000;
end
position = 40;
end
trajectory = zeros(1, n_steps);
end
for i = 1:n_steps
bubble_time = toc;
step = 2*(rand > 0.5) - 1; % +1 or -1
% MATLAB sort
position = position + step;
tic;
trajectory(i) = position;
matlab_sorted = sort(data);
end
matlab_time = toc;
% Frequency distribution
fprintf('Bubble Sort: %.4f sec\nMATLAB
edges = min(trajectory):max(trajectory);
sort: %.4f sec\n', ...
counts = histcounts(trajectory, edges);
bubble_time, matlab_time);
figure;
%% Student Structure Array
bar(edges(1:end-1), counts);
students = struct('name', {}, 'id', {},
title('1D Random Walk Frequency
'marks', {});
Distribution');
% Add students
xlabel('Position');
students(1).name = 'Alice';
ylabel('Frequency');
students(1).id = 101;
grid on;
students(1).marks = [85, 92, 78];
%% Test Score Analysis
students(2).name = 'Bob';
scores = randi([40 100], 1, 200); % Random
students(2).id = 102;
scores 40-100
students(2).marks = [72, 68, 81];
% 10-bin histogram
% Cell array example
figure;
class_data = {'Math101', [1:10], students};
histogram(scores, 10);
% Access data
title('Test Scores: 10 Bins');
fprintf('%s (ID: %d) has average %.1f\n',
xlabel('Score');
...
ylabel('Frequency');
students(1).name, students(1).id,
grid on;
mean(students(1).marks));

>> chapter11 Score Range 60-70 28 Bubble Sort: 0.0020 sec


Count 70-80 40 MATLAB sort: 0.0002 sec
Enter time step: 5 40-50 35 80-90 29 Alice (ID: 101) has average
50-60 29 90-100 39 85.0>>

You might also like