0% found this document useful (0 votes)
22 views

MATLAB Snippet Code

Snippet code for MATLAB

Uploaded by

Apple Man
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)
22 views

MATLAB Snippet Code

Snippet code for MATLAB

Uploaded by

Apple Man
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

MATLAB Tutorial

Basic Commands
help: Provides help for MATLAB functions.
doc: Opens the documentation for a function.
clc: Clears the command window.
clear: Removes variables from the workspace.
who: Lists variables in the workspace.
whos: Lists variables with detailed information.
load: Loads variables from a file.
save: Saves variables to a file.
exit or quit: Exits MATLAB.

Mathematical Operations
+, -, *, /, ^: Basic arithmetic operators.
sum, prod, mean, median, std: Basic statistical operations.
sqrt, exp, log, log10: Square root, exponential, and logarithmic functions.
sin, cos, tan, asin, acos, atan: Trigonometric functions.
round, ceil, floor, fix: Rounding functions.

Matrix and Array Operations


zeros, ones, eye: Create matrices of zeros, ones, or an identity matrix.
size, length: Determine the size or length of an array.
reshape, transpose ('): Reshape or transpose matrices.
inv, det, rank: Matrix inversion, determinant, and rank.
dot, cross: Dot product and cross product.
linspace, logspace: Generate linearly or logarithmically spaced vectors.

Data Visualization
plot: Create 2D plots.
hold on/off: Add multiple plots to the same figure.
xlabel, ylabel, title: Add labels and titles to plots.
legend: Add a legend to a plot.
grid: Add a grid to a plot.
bar, scatter, hist: Create bar, scatter, and histogram plots.
surf, mesh: Create 3D surface and mesh plots.

File I/O
fopen, fclose: Open and close files.
fread, fwrite: Read and write binary data.
fprintf, fscanf: Write and read formatted data.

Programming Constructs
if, elseif, else: Conditional statements.
for: Loop over a sequence of values.
while: Loop while a condition is true.
switch, case: Conditional execution based on multiple cases.
break, continue: Control loop execution.
function: Define a new function.
return: Return control from a function.

Advanced Mathematical Functions


eig: Compute eigenvalues and eigenvectors.
svd: Singular value decomposition.
fft: Fast Fourier Transform.
conv: Convolution of vectors.
gradient, diff: Compute numerical gradients or differences.
Toolboxes and Specialized Commands
optimtool: Optimization Toolbox.
simulink: Open Simulink for modeling and simulation.
image, imshow: Display images.
audioread, audiowrite: Read and write audio files.

Debugging Commands
dbstop: Set a breakpoint.
dbclear: Clear breakpoints.
dbstep: Step through code.
dbquit: Quit debugging mode.
disp: Display a message or variable.
Basic Code Snippets

-----------------------------------------------------------------------------------------------------------
Basic Operations
% Define variables
a = 5;
b = 3;
% Perform basic arithmetic
sum = a + b;
difference = a - b;
product = a * b;
quotient = a / b;

-----------------------------------------------------------------------------------------------------------
Matrix and Array Operations
% Create a 3x3 matrix
A = [1 2 3; 4 5 6; 7 8 9];
% Transpose
AT = A';
% Inverse
A_inv = inv(A);
% Element-wise operations
B = A .* 2; % Multiply each element by 2

-----------------------------------------------------------------------------------------------------------
Conditional Statements
x = 10;
% If-else statement
if x > 5
disp('x is greater than 5');
else
disp('x is less than or equal to 5');
end

-----------------------------------------------------------------------------------------------------------
Loops
% For loop
for i = 1:5
fprintf('Iteration: %d\n', i);
end
% While loop
counter = 1;
while counter <= 5
fprintf('Counter: %d\n', counter);
counter = counter + 1;
end

-----------------------------------------------------------------------------------------------------------
Plotting
% Define data
x = 0:0.1:2*pi;
y = sin(x);
% Create a plot
plot(x, y, 'r-=');
xlabel('x-axis');
ylabel('y-axis');
title('Sine Wave');
grid on;

-----------------------------------------------------------------------------------------------------------
Functions
% Define a function to calculate the square of a number
function result = squareNumber(x)
result = x^2;
end
% Call the function
result = squareNumber(4);
disp(result); % Outputs 16
-----------------------------------------------------------------------------------------------------------
File I/O
% Write data to a file
data = [1, 2, 3; 4, 5, 6];
save('data.mat', 'data');
% Load data from a file
load('data.mat');
disp(data);

-----------------------------------------------------------------------------------------------------------
Numerical Methods
% Solve a linear equation system: Ax = b
A = [2 1; 1 3];
b = [8; 13];
x = A\b; % Solve for x
disp(x);

-----------------------------------------------------------------------------------------------------------
Image Processing
% Read and display an image
img = imread('image.jpg');
imshow(img);
% Convert to grayscale
grayImg = rgb2gray(img);
imshow(grayImg);

-----------------------------------------------------------------------------------------------------------
Random Number Generation
% Generate random numbers
randNum = rand(1, 10); % 10 random numbers between 0 and 1
randInt = randi([1, 100], 1, 5); % 5 random integers between 1 and 100

-----------------------------------------------------------------------------------------------------------
Debugging
% Example function to debug
function debugExample()
a = 10;
b = 0;
c = a / b; % Division by zero error
end
% Set a breakpoint
dbstop if error;
% Call the function
debugExample();
Math Code Snippets

-----------------------------------------------------------------------------------------------------------
Differentiation
syms x; % Define symbolic variable
f = x^3 + 2*x^2 + 5*x + 10; % Define a function
% Differentiate the function
df = diff(f, x);
disp(df); % Output: 3*x^2 + 4*x + 5

-----------------------------------------------------------------------------------------------------------
Numerical Differentiation
x = 0:0.1:10;
y = x.^2; % Example function
dy = diff(y) ./ diff(x); % First derivative approximation
plot(x(1:end-1), dy); % Plot derivative

-----------------------------------------------------------------------------------------------------------
Partial Fraction Decomposition
syms s; % Define symbolic variable
num = s^2 + 5; % Numerator of the fraction
den = (s + 1)*(s^2 + 3*s + 2); % Denominator
% Perform partial fraction decomposition
[residues, poles, directTerm] = residue(sym2poly(num), sym2poly(den));
disp(residues); % Coefficients of partial fractions
disp(poles); % Roots of the denominator
disp(directTerm); % Direct term if any

-----------------------------------------------------------------------------------------------------------
Symbolic Integration
syms x;
f = x^2 + 3*x + 2;
% Indefinite integral
indef_integral = int(f, x);
disp(indef_integral);
% Definite integral
def_integral = int(f, x, 0, 2);
disp(def_integral);

-----------------------------------------------------------------------------------------------------------
Numerical Integration
f = @(x) x.^2 + 3*x + 2; % Define the function
result = integral(f, 0, 2); % Definite integral from 0 to 2
disp(result);

-----------------------------------------------------------------------------------------------------------
Root Finding (Newton-Raphson Method)
f = @(x) x^3 - 6*x^2 + 11*x - 6; % Example function
df = @(x) 3*x^2 - 12*x + 11; % Derivative
x0 = 2; % Initial guess
tol = 1e-6; % Tolerance
while abs(f(x0)) > tol
x0 = x0 - f(x0)/df(x0); % Newton-Raphson formula
end
disp(x0); % Display the root

-----------------------------------------------------------------------------------------------------------
Solving Differential Equations (ODEs)
% Define ODE: dy/dx = -2y
f = @(x, y) -2*y;
% Solve ODE using ode45
[x, y] = ode45(f, [0 5], 1); % [0 5] is the interval, 1 is the initial condition
plot(x, y);
xlabel('x'); ylabel('y');
title('Solution of dy/dx = -2y');
-----------------------------------------------------------------------------------------------------------
Laplace Transform
syms t s;
f = exp(-2*t); % Time-domain function
% Laplace Transform
F = laplace(f, t, s);
disp(F);
% Inverse Laplace Transform
f_inv = ilaplace(F, s, t);
disp(f_inv);

-----------------------------------------------------------------------------------------------------------
Creating a Transfer Function
numerator = [1 5]; % Coefficients of numerator
denominator = [1 6 11 6]; % Coefficients of denominator
sys = tf(numerator, denominator); % Create transfer function
disp(sys);

Bode Plot and Step Response


% Bode plot
bode(sys);
grid on;
% Step response
step(sys);
grid on;

Simulating a Control System


% Open-loop system
sys = tf([1], [1 3 2]); % Example transfer function
% Closed-loop system with feedback gain
K = 2;
closed_loop_sys = feedback(K*sys, 1);
% Step response
step(closed_loop_sys);
grid on;

-----------------------------------------------------------------------------------------------------------
Solving State-Space Models
A = [0 1; -2 -3]; % State matrix
B = [0; 1]; % Input matrix
C = [1 0]; % Output matrix
D = 0; % Direct transmission
% Create state-space model
sys = ss(A, B, C, D);
% Step response
step(sys);
grid on;
Electrical Circuit Methods

-----------------------------------------------------------------------------------------------------------
Ohm’s Law
V = 10; % Voltage in volts
R = 5; % Resistance in ohms
% Calculate current
I = V / R;
disp('Current (Ohm''s Law):');
disp(I);

-----------------------------------------------------------------------------------------------------------
Transient Response of an RC Circuit
R = 1e3; % Resistance in ohms
C = 1e-6; % Capacitance in farads
t = 0:1e-6:0.01; % Time vector (0 to 0.01 seconds)
% Voltage response for charging a capacitor
V = 5 * (1 - exp(-t / (R*C))); % Assuming a 5V source
plot(t, V);
xlabel('Time (s)');
ylabel('Voltage (V)');
title('RC Circuit Voltage Response');
grid on;

-----------------------------------------------------------------------------------------------------------
Laplace Transform
syms t s;
f = exp(-2*t); % Example time-domain function
% Laplace Transform
F = laplace(f, t, s);
disp('Laplace Transform:');
disp(F);
% Inverse Laplace Transform
f_inv = ilaplace(F, s, t);
disp('Inverse Laplace Transform:');
disp(f_inv);

-----------------------------------------------------------------------------------------------------------
Transfer Function and Step Response
numerator = [1 5]; % Coefficients of numerator
denominator = [1 6 11 6]; % Coefficients of denominator
% Define transfer function
sys = tf(numerator, denominator);
% Step response
step(sys);
title('Step Response of Transfer Function');
grid on;

-----------------------------------------------------------------------------------------------------------
Fourier Transform
% Time-domain signal
t = 0:0.001:1; % Time vector
x = sin(2*pi*50*t) + sin(2*pi*120*t); % Composite signal
% Fourier Transform
X = fft(x);
f = linspace(0, 1/(2*(t(2)-t(1))), numel(t)/2); % Frequency axis
% Plot the magnitude spectrum
plot(f, abs(X(1:numel(f))));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Fourier Transform');
grid on;
-----------------------------------------------------------------------------------------------------------
RLC Circuit Resonance
R = 10; % Resistance in ohms
L = 1e-3; % Inductance in henries
C = 1e-6; % Capacitance in farads
f = 0:1:20000; % Frequency range (0 to 20 kHz)
% Calculate impedance
omega = 2*pi*f;
Z = sqrt(R^2 + (omega*L - 1./(omega*C)).^2);
% Plot impedance
plot(f, Z);
xlabel('Frequency (Hz)');
ylabel('Impedance (Ohms)');
title('RLC Circuit Resonance');
grid on;

-----------------------------------------------------------------------------------------------------------
State-Space Representation
A = [0 1; -2 -3]; % State matrix
B = [0; 1]; % Input matrix
C = [1 0]; % Output matrix
D = 0; % Direct transmission term
% State-space model
sys = ss(A, B, C, D);
% Step response
step(sys);
title('State-Space Step Response');
grid on;

-----------------------------------------------------------------------------------------------------------
Cramer’s Rule
% Coefficient matrix A
A = [2 3 -1; 1 2 1; 3 -1 2];
% Constants vector b
b = [5; 4; 3];
% Determinant of A
det_A = det(A);
% Check if the system has a unique solution
if det_A == 0
disp('The system has no unique solution (det(A) = 0).');
else
% Number of variables
n = size(A, 1);
% Initialize solution vector
x = zeros(n, 1);
% Solve for each variable using Cramer's Rule
for i = 1:n
A_i = A; % Copy A
A_i(:, i) = b; % Replace the i-th column with b
det_A_i = det(A_i); % Compute determinant of modified matrix
x(i) = det_A_i / det_A; % Calculate x_i
end
% Display the solution
disp('Solution using Cramer''s Rule:');
disp(x);
end

-----------------------------------------------------------------------------------------------------------
Mesh Analysis
% Coefficients matrix for mesh currents
R1 = 10; R2 = 20; R3 = 30; V1 = 10;
A = [R1 + R2, -R2; -R2, R2 + R3];
% Voltage sources
b = [V1; 0];
% Solve for mesh currents
I = A \ b;
disp('Mesh currents (in Amperes):');
disp(I);
-----------------------------------------------------------------------------------------------------------
Kirchhoff’s Voltage Law
% Example: Two loops
V1 = 10; R1 = 5; R2 = 10; R3 = 15;
% Loop equations: V1 = I1*R1 + I2*R2
% 0 = I2*R2 + I2*R3
A = [R1, R2; R2, R2 + R3];
b = [V1; 0];
% Solve currents
I = A \ b;
disp('Currents using KVL (in Amperes):');
disp(I);

-----------------------------------------------------------------------------------------------------------
Kirchhoff’s Current Law
% Node equations: I1 - I2 - I3 = 0
% I2 - I4 = 0
G1 = 1/10; G2 = 1/20; G3 = 1/30; % Conductances (1/R)
A = [G1 + G2 + G3, -G2; -G2, G2 + G3];
b = [0; 0];
% Solve for node voltages
V = A \ b;
disp('Node voltages using KCL (in Volts):');
disp(V);

-----------------------------------------------------------------------------------------------------------
Maximum Power Transfer
Rs = 10; % Source resistance
Rl = Rs; % For maximum power transfer, Rl = Rs
disp('Load resistance for maximum power transfer:');
disp(Rl);

-----------------------------------------------------------------------------------------------------------
Thevenin’s Theorem
% Step 1: Calculate Thevenin voltage (Vth)
R1 = 6; R2 = 12; R3 = 18; V1 = 24;
Vth = V1 * (R3 / (R2 + R3)); % Voltage divider rule
% Step 2: Calculate Thevenin resistance (Rth)
Rth = (R1 * (R2 + R3)) / (R1 + R2 + R3);
disp('Thevenin equivalent voltage (Vth):');
disp(Vth);
disp('Thevenin equivalent resistance (Rth):');
disp(Rth);

-----------------------------------------------------------------------------------------------------------
Nodal Analysis
% Admittances (1/R)
G1 = 1/R1; G2 = 1/R2; G3 = 1/R3;
% Nodal equations
A = [G1 + G2, -G2; -G2, G2 + G3];
b = [G1 * V1; 0];
% Solve for node voltages
V = A \ b;
disp('Node voltages using nodal analysis (in Volts):');
disp(V);

-----------------------------------------------------------------------------------------------------------
Superposition Theorem
% Contribution of V1 alone
R1 = 10; R2 = 20; V1 = 10; V2 = 5;
I1 = V1 / (R1 + R2);
% Contribution of V2 alone
I2 = -V2 / (R1 + R2);
% Total current using superposition
I_total = I1 + I2;
disp('Total current using superposition (in Amperes):');
disp(I_total);
-----------------------------------------------------------------------------------------------------------
Resonance in RLC Circuits
L = 10e-3; % Inductance in Henrys
C = 100e-6; % Capacitance in Farads
% Resonant frequency
f_res = 1 / (2 * pi * sqrt(L * C));
disp('Resonant frequency (in Hz):');
disp(f_res);

-----------------------------------------------------------------------------------------------------------
Operational Amplifier (Inverting Amplifier)
R1 = 1e3; % Input resistor
R2 = 10e3; % Feedback resistor
Vin = 1; % Input voltage
% Output voltage
Vout = -R2 / R1 * Vin;
disp('Output voltage of inverting amplifier (in Volts):');
disp(Vout);

-----------------------------------------------------------------------------------------------------------
Delta-Wye Transformation
% Delta resistances
R_AB = 12;
R_BC = 18;
R_CA = 24;
% Wye resistances
R_A = (R_AB * R_CA) / (R_AB + R_BC + R_CA);
R_B = (R_AB * R_BC) / (R_AB + R_BC + R_CA);
R_C = (R_BC * R_CA) / (R_AB + R_BC + R_CA);
disp('Wye equivalent resistances:');
disp(['R_A = ', num2str(R_A), ' Ω']);
disp(['R_B = ', num2str(R_B), ' Ω']);
disp(['R_C = ', num2str(R_C), ' Ω']);

-----------------------------------------------------------------------------------------------------------
Maximum Efficiency of Transformer
% Parameters
P_fe = 50; % Core (iron) losses in Watts
P_cu = P_fe; % Copper losses equal to iron losses
disp('Transformer operates at maximum efficiency when copper losses equal core losses.');
disp(['Copper losses (P_cu) = ', num2str(P_cu), ' W']);

-----------------------------------------------------------------------------------------------------------
RC Low-Pass Filter
R = 1e3; % Resistance in Ohms
C = 1e-6; % Capacitance in Farads
f = logspace(1, 5, 100); % Frequency range (10 Hz to 100 kHz)
omega = 2 * pi * f;
% Transfer function magnitude
H = 1 ./ sqrt(1 + (omega * R * C).^2);
% Plot frequency response
semilogx(f, 20 * log10(H));
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('RC Low-Pass Filter Frequency Response');
grid on;

-----------------------------------------------------------------------------------------------------------
RLC Bandpass Filter
R = 10; % Resistance in Ohms
L = 1e-3; % Inductance in Henrys
C = 100e-6; % Capacitance in Farads
f = logspace(1, 5, 500); % Frequency range (10 Hz to 100 kHz)
omega = 2 * pi * f;
% Transfer function
H = (omega .* R * C) ./ sqrt((1 - (omega.^2 * L * C)).^2 + (omega .* R * C).^2);
% Plot frequency response
semilogx(f, 20 * log10(H));
xlabel('Frequency (Hz)');
ylabel('Magnitude (dB)');
title('RLC Bandpass Filter Frequency Response');
grid on;
-----------------------------------------------------------------------------------------------------------
RMS Value of a Sinusoidal Signal
V_peak = 10; % Peak voltage
V_rms = V_peak / sqrt(2);
disp('RMS value of the sinusoidal signal:');
disp([num2str(V_rms), ' V']);

-----------------------------------------------------------------------------------------------------------
Norton’s Theorem
R1 = 5; R2 = 10; V1 = 15;
% Norton current
IN = V1 / (R1 + R2);
% Norton resistance
RN = (R1 * R2) / (R1 + R2);
disp('Norton equivalent current (IN):');
disp([num2str(IN), ' A']);
disp('Norton equivalent resistance (RN):');
disp([num2str(RN), ' Ω']);

-----------------------------------------------------------------------------------------------------------
Star-Delta Transformation
% Star resistances
R_A = 5; R_B = 10; R_C = 15;
% Delta resistances
R_AB = (R_A * R_B + R_B * R_C + R_C * R_A) / R_C;
R_BC = (R_A * R_B + R_B * R_C + R_C * R_A) / R_A;
R_CA = (R_A * R_B + R_B * R_C + R_C * R_A) / R_B;
disp('Delta equivalent resistances:');
disp(['R_AB = ', num2str(R_AB), ' Ω']);
disp(['R_BC = ', num2str(R_BC), ' Ω']);
disp(['R_CA = ', num2str(R_CA), ' Ω']);

-----------------------------------------------------------------------------------------------------------
Bode Plot
R = 1e3; % Resistance in Ohms
C = 1e-6; % Capacitance in Farads
% Transfer function
s = tf('s');
H = 1 / (s * R * C + 1);
% Plot Bode plot
bode(H);
grid on;
title('Bode Plot of a Low-Pass Filter');

-----------------------------------------------------------------------------------------------------------
Voltage Divider
R1 = 10; % Resistor 1 in Ohms
R2 = 20; % Resistor 2 in Ohms
Vin = 12; % Input voltage in Volts
% Output voltage
Vout = Vin * (R2 / (R1 + R2));
disp('Output voltage using voltage divider rule:');
disp([num2str(Vout), ' V']);
Mechanical Systems

-----------------------------------------------------------------------------------------------------------
Free Vibration of a Single Degree-of-Freedom (SDOF) System
% Parameters
m = 1; % Mass (kg)
k = 100; % Stiffness (N/m)
c = 2; % Damping coefficient (Ns/m)
% Natural frequency and damping ratio
omega_n = sqrt(k/m); % Natural frequency (rad/s)
zeta = c / (2 * sqrt(k * m)); % Damping ratio
% Time vector
t = 0:0.01:10; % Time (s)
% Initial conditions
x0 = 0.1; % Initial displacement (m)
v0 = 0; % Initial velocity (m/s)
% Solution for underdamped case (zeta < 1)
if zeta < 1
omega_d = omega_n * sqrt(1 - zeta^2); % Damped natural frequency
x = exp(-zeta * omega_n * t) .* (x0 * cos(omega_d * t) + .==
(v0 + zeta * omega_n * x0) / omega_d * sin(omega_d * t));
end
% Plot response
plot(t, x);
xlabel('Time (s)');
ylabel('Displacement (m)');
title('Free Vibration of an SDOF System');
grid on;

-----------------------------------------------------------------------------------------------------------
Forced Vibration of SDOF System
% Parameters
m = 1; k = 100; c = 2; % Mass, stiffness, damping
F0 = 10; omega = 5; % Forcing amplitude and frequency
% Time vector
t = 0:0.01:10;
% Steady-state response
omega_n = sqrt(k/m);
zeta = c / (2 * sqrt(k * m));
omega_d = omega_n * sqrt(1 - zeta^2);
X = F0 / sqrt((k - m * omega^2)^2 + (c * omega)^2); % Amplitude
phi = atan2(c * omega, k - m * omega^2); % Phase angle
x = X * sin(omega * t - phi); % Response
% Plot response
plot(t, x);
xlabel('Time (s)');
ylabel('Displacement (m)');
title('Forced Vibration of an SDOF System');
grid on;

-----------------------------------------------------------------------------------------------------------
Two-Degree-of-Freedom (2DOF) System
% Parameters
m1 = 1; m2 = 2; % Masses (kg)
k1 = 100; k2 = 200; % Stiffnesses (N/m)
% Mass and stiffness matrices
M = [m1 0; 0 m2];
K = [k1 + k2, -k2; -k2, k2];
% Solve eigenvalue problem
[V, D] = eig(K, M); % Modes and natural frequencies
% Extract natural frequencies
omega_n1 = sqrt(D(1, 1)); % First natural frequency
omega_n2 = sqrt(D(2, 2)); % Second natural frequency
disp('Natural frequencies (rad/s):');
disp([omega_n1, omega_n2]);
disp('Mode shapes:');
disp(V);
-----------------------------------------------------------------------------------------------------------
Simple Pendulum Simulation
% Parameters
L = 1; % Length of pendulum (m)
g = 9.81; % Gravitational acceleration (m/s^2)
theta0 = deg2rad(10); % Initial angle (rad)
% Time vector
t = 0:0.01:10;
% Equation of motion
theta = theta0 * cos(sqrt(g/L) * t);
% Plot response
plot(t, rad2deg(theta));
xlabel('Time (s)');
ylabel('Angle (degrees)');
title('Simple Pendulum Motion');
grid on;

-----------------------------------------------------------------------------------------------------------
Rotational Mechanical System
% Parameters
J = 0.01; % Moment of inertia (kg·m^2)
c = 0.1; % Damping coefficient (N·m·s/rad)
T0 = 5; omega_t = 2; % Torque amplitude and frequency
% Time vector
t = 0:0.01:10;
% Rotational response
omega = (T0 / sqrt(c^2 + (J * omega_t^2)^2)) * sin(omega_t * t);
% Plot angular velocity
plot(t, omega);
xlabel('Time (s)');
ylabel('Angular Velocity (rad/s)');
title('Rotational Mechanical System Response');
grid on;

-----------------------------------------------------------------------------------------------------------
Beam Deflection (Euler-Bernoulli Beam Theory)
% Parameters
L = 2; % Length of beam (m)
P = 500; % Load (N)
E = 2e11; % Young's modulus (Pa)
I = 5e-6; % Moment of inertia (m^4)
% Displacement along beam
x = linspace(0, L, 100); % Position along beam
y = (P / (6 * E * I)) * (x.^3 - 3 * L * x.^2 + 2 * L^2 * x);
% Plot deflection
plot(x, y);
xlabel('Position along beam (m)');
ylabel('Deflection (m)');
title('Beam Deflection');
grid on;

-----------------------------------------------------------------------------------------------------------
Control of Mechanical System
% System parameters
m = 1; k = 100; c = 10; % Mass, stiffness, damping
% Transfer function of the system
s = tf('s');
G = 1 / (m * s^2 + c * s + k);
% PID controller
Kp = 100; Ki = 1; Kd = 10;
PID = Kp + Ki/s + Kd * s;
% Closed-loop system
T = feedback(PID * G, 1);
% Step response
step(T);
title('PID Controlled Mass-Spring-Damper System');
grid on;
-----------------------------------------------------------------------------------------------------------
Gear Ratio Calculation
% Number of teeth on input and output gears
N1 = 20; % Input gear
N2 = 40; % Output gear
% Gear ratio
gear_ratio = N2 / N1;
disp('Gear Ratio:');
disp(gear_ratio);

-----------------------------------------------------------------------------------------------------------
Angular Velocity Relationship
% Input angular velocity (rad/s)
omega1 = 100;
% Gear ratio
gear_ratio = 2; % R = N2 / N1
% Output angular velocity
omega2 = omega1 / gear_ratio;
disp('Output Angular Velocity (rad/s):');
disp(omega2);

-----------------------------------------------------------------------------------------------------------
Torque Transfer Between Gears
% Input torque (N·m)
T1 = 50;
% Gear ratio
gear_ratio = 2; % R = N2 / N1
% Output torque
T2 = T1 * gear_ratio;
disp('Output Torque (N·m):');
disp(T2);

-----------------------------------------------------------------------------------------------------------
Efficiency in Gear Systems
% Input power (W)
P_in = 500;
% Efficiency
eta = 0.9; % 90%
% Output power
P_out = P_in * eta;
disp('Output Power (W):');
disp(P_out);

-----------------------------------------------------------------------------------------------------------
Simulation of Gear Train Dynamics
% Gear teeth
N1 = 20; % Gear 1
N2 = 40; % Gear 2
N3 = 60; % Gear 3
% Input angular velocity
omega1 = 100; % rad/s
% Angular velocities
omega2 = omega1 * (N1 / N2);
omega3 = omega2 * (N2 / N3);
disp('Angular Velocities (rad/s):');
disp(['Gear 2: ', num2str(omega2)]);
disp(['Gear 3: ', num2str(omega3)]);
-----------------------------------------------------------------------------------------------------------
Spur Gear Force Analysis
% Input parameters
T1 = 50; % Torque (N·m)
r1 = 0.1; % Radius of gear (m)
phi = deg2rad(20); % Pressure angle (rad)
% Tangential force
Ft = T1 / r1;
% Radial force
Fr = Ft * tan(phi);
% Normal force
Fn = Ft / cos(phi);
disp('Forces on the Spur Gear (N):');
disp(['Tangential Force (Ft): ', num2str(Ft)]);
disp(['Radial Force (Fr): ', num2str(Fr)]);
disp(['Normal Force (Fn): ', num2str(Fn)]);

-----------------------------------------------------------------------------------------------------------
Velocity Analysis in Compound Gear Train
% Number of teeth
N1 = 20; N2 = 40; N3 = 30; N4 = 60;
% Input angular velocity
omega1 = 100; % rad/s
% Compound gear train analysis
omega2 = omega1 * (N1 / N2);
omega3 = omega2 * (N2 / N3);
omega4 = omega3 * (N3 / N4);
disp('Angular Velocities in Compound Gear Train (rad/s):');
disp(['Gear 2: ', num2str(omega2)]);
disp(['Gear 3: ', num2str(omega3)]);
disp(['Gear 4: ', num2str(omega4)]);

-----------------------------------------------------------------------------------------------------------
Dynamic Simulation of Gearbox
% Parameters
J1 = 0.01; % Inertia of gear 1 (kg·m^2)
J2 = 0.02; % Inertia of gear 2 (kg·m^2)
k = 100; % Stiffness of coupling (N·m/rad)
T1 = 10; % Input torque (N·m)
% Time vector
t = 0:0.01:5;
% Differential equations
dynamics = @(t, y) [y(2); .==
(-k / J1) * (y(1) - y(3)) + T1 / J1; .==
y(4); .==
(-k / J2) * (y(3) - y(1))];
% Initial conditions
y0 = [0; 0; 0; 0]; % [theta1, omega1, theta2, omega2]
% Solve ODE
[t, y] = ode45(dynamics, t, y0);
% Plot angular displacements
plot(t, y(:, 1), t, y(:, 3));
legend('Gear 1 Displacement', 'Gear 2 Displacement');
xlabel('Time (s)');
ylabel('Angular Displacement (rad)');
title('Gearbox Dynamics');
grid on;

-----------------------------------------------------------------------------------------------------------
Helical Gear Contact Stress
% Input parameters
P = 10e3; % Power (W)
V = 5; % Pitch line velocity (m/s)
b = 0.02; % Face width (m)
dp = 0.15; % Pitch diameter (m)
phi = deg2rad(20); % Helix angle (rad)
% Contact stress
Ft = P / V; % Tangential force
K = 1.2; % Geometry factor
stress = K * sqrt(Ft / (b * dp * cos(phi)));
disp('Contact Stress (Pa):');
disp(stress);
-----------------------------------------------------------------------------------------------------------
Test Code
% MATLAB Test Script
clc; % Clear the command window
clear; % Clear workspace variables
close all; % Close all figure windows
disp('MATLAB is working correctly!'); % Display a message
% Generate data for a sine wave
t = 0:0.01:2*pi; % Time vector from 0 to 2π with step size 0.01
y = sin(t); % Sine function
% Plot the sine wave
figure;
plot(t, y, 'b-', 'LineWidth', 2); % Plot sine wave with blue line
title('Sine Wave Test');
xlabel('Time (s)');
ylabel('Amplitude');
grid on; % Turn on the grid
legend('sin(t)');
% Display the maximum and minimum values of the sine wave
maxValue = max(y);
minValue = min(y);
fprintf('Maximum Value: %.2f\n', maxValue);
fprintf('Minimum Value: %.2f\n', minValue);

-----------------------------------------------------------------------------------------------------------
Test Code
% MATLAB Tangent Function Test Script
clc; % Clear the command window
clear; % Clear workspace variables
close all; % Close all figure windows
disp('MATLAB is working correctly with the Tangent Function!'); % Display a message
% Generate data for the tangent function
t = -pi:0.01:pi; % Time vector from -π to π with step size 0.01
y = tan(t); % Tangent function
% Avoiding asymptotes by setting limits for large tangent values
y(abs(y) > 10) = NaN; % Set values greater than 10 or less than -10 to NaN
% Plot the tangent function
figure;
plot(t, y, 'r-', 'LineWidth', 2); % Plot tangent wave with red line
title('Tangent Function Test');
xlabel('Time (radians)');
ylabel('Amplitude');
grid on; % Turn on the grid
legend('tan(t)');
% Display some statistical information about the tangent values
maxValue = max(y(~isnan(y))); % Maximum value ignoring NaNs
minValue = min(y(~isnan(y))); % Minimum value ignoring NaNs
fprintf('Maximum Tangent Value: %.2f\n', maxValue);
fprintf('Minimum Tangent Value: %.2f\n', minValue);

-----------------------------------------------------------------------------------------------------------
Test Code
% MATLAB Test Script for Sin, Cos, and Tan Functions
clc; % Clear the command window
clear; % Clear workspace variables
close all; % Close all figure windows
disp('MATLAB is working correctly with Sin, Cos, and Tan functions!'); % Display a message
% Generate data for the trigonometric functions
t = -2*pi:0.01:2*pi; % Time vector from -2π to 2π with step size 0.01
y_sin = sin(t); % Sine function
y_cos = cos(t); % Cosine function
y_tan = tan(t); % Tangent function
% Handle tangent asymptotes by setting limits for large tangent values
y_tan(abs(y_tan) > 10) = NaN; % Set tangent values beyond ±10 to NaN to avoid asymptotes
% Plot all three functions on the same figure
figure;
plot(t, y_sin, 'b-', 'LineWidth', 2); % Plot sine with blue line
hold on; % Hold the plot for additional plots
plot(t, y_cos, 'g-', 'LineWidth', 2); % Plot cosine with green line
plot(t, y_tan, 'r-', 'LineWidth', 2); % Plot tangent with red line
% Adding labels, title, and legend
title('Sin, Cos, and Tan Functions');
xlabel('Time (radians)');
ylabel('Amplitude');
grid on; % Turn on the grid
legend('sin(t)', 'cos(t)', 'tan(t)', 'Location', 'best');
hold off;
% Display some statistical information in the Command Window
fprintf('Max Sin Value: %.2f, Min Sin Value: %.2f\n', max(y_sin), min(y_sin));
fprintf('Max Cos Value: %.2f, Min Cos Value: %.2f\n', max(y_cos), min(y_cos));
fprintf('Max Tan Value: %.2f, Min Tan Value: %.2f\n', max(y_tan(~isnan(y_tan))), min(y_tan(~isnan(y_tan))));

You might also like