Lesson 08-Advanced Numerical Computation

Nonlinear Equation Solving Techniques

Single-Variable Equation Solving

In-Depth Application of fzero Function:

% Basic usage: Solve nonlinear equation
f = @(x) x^3 - 2*x - 5;
x0 = 2;  % Initial guess
root = fzero(f, x0);  % Solve

% Specify solution interval
root_interval = fzero(f, [1,3]);  % Solve in [1,3] interval

% Advanced options configuration
options = optimset('Display','iter','TolX',1e-10,'FunValCheck','on');
root_optimized = fzero(f, x0, options);

% Handling complex roots
f_complex = @(x) x^2 + 1;
root_complex = fzero(f_complex, 1i);  % Start from imaginary initial value

Engineering Application Case:

% Circuit analysis: Solve nonlinear resistance equation
R_nonlinear = @(V) 10 + 0.1*V^2;  % Nonlinear resistance characteristic
I_target = 0.5;  % Target current
V_solution = fzero(@(V) R_nonlinear(V)*V - I_target, 5);
fprintf('Voltage required to achieve %.2fA current: %.4fV\n', I_target, V_solution);

Multivariable Equation System Solving

Advanced Application of fsolve:

% Nonlinear system definition
fun = @(x) [x(1)^2 + x(2)^2 - 4;  % x² + y² = 4
            exp(x(1)) + x(2) - 3]; % e^x + y = 3

% Initial guess
x0 = [1; 1];

% Basic solving
solution = fsolve(fun, x0);

% Provide Jacobian matrix (accelerate convergence)
jac = @(x) [2*x(1), 2*x(2); 
            exp(x(1)), 1];
solution_jac = fsolve(fun, x0, optimoptions('fsolve','Jacobian',jac));

% Constrained optimization (combined with fmincon)
lb = [-10;-10]; ub = [10;10];
solution_constrained = fmincon(@(x)norm(fun(x)), x0, [],[],[],[],lb,ub);

Practical Engineering Case:

% Mechanical system equilibrium equations
% Define nonlinear system (spring-mass system)
k1 = 100; k2 = 150; m = 2;
fun_mech = @(x) [m*x(2)^2 + k1*x(1) - 100;  % Energy conservation equation
                 x(1) - x(2)^2 - 5];        % Displacement relation equation

% Solve and verify
sol_mech = fsolve(fun_mech, [1;1]);
fprintf('Equilibrium position: x=%.4f, v=%.4f\n', sol_mech(1), sol_mech(2));
residual = norm(fun_mech(sol_mech));  % Residual check

Partial Differential Equation Solving Techniques

PDE Toolbox Application

Advanced Usage of pdepe Function:

% Define PDE coefficients
function [c,f,s] = heatPDE(x,t,u,DuDx)
    c = 1;                   % Heat capacity
    f = 0.1*DuDx;            % Diffusion term (damping coefficient 0.1)
    s = sin(pi*x);           % Heat source term
end

% Initial condition
function u0 = ic(x)
    u0 = sin(pi*x);          % Initial temperature distribution
end

% Boundary conditions
function [pl,ql,pr,qr] = bc(xl,ul,xr,ur,t)
    pl = ul; ql = 0;         % Left end fixed temperature
    pr = 0; qr = 1;          % Right end insulated
end

% Solving setup
m = 0;                     % Planar problem
x = linspace(0,1,20);      % Spatial grid
t = linspace(0,0.5,10);    % Time grid
sol = pdepe(m,@heatPDE,@ic,@bc,x,t);

% Result visualization
surf(x,t,sol);
xlabel('Spatial Position'); ylabel('Time'); zlabel('Temperature');

pdetool Graphical Interface Operation:

% Launch PDE Toolbox
pdetool

% Graphical interface operation workflow:
% 1. Select problem type (steady-state/transient/eigenvalue)
% 2. Draw geometry (rectangle/circle/polygon)
% 3. Define boundary conditions (Dirichlet/Neumann)
% 4. Set PDE coefficients (linear/nonlinear)
% 5. Mesh generation and refinement
% 6. Solve and post-processing
% 7. Export results to workspace

Custom PDE Solving

Finite Element Method Implementation:

% Simple 1D finite element implementation
function u = solve1DFEM()
    % Problem definition: -u'' = f, u(0)=0, u(1)=0
    f = @(x) 2*pi^2*sin(pi*x);  % Right-hand side
    exact = @(x) sin(pi*x);      % Exact solution
    
    % Mesh generation
    n = 20; h = 1/n;
    x = linspace(0,1,n+1)';
    
    % Assemble stiffness matrix
    A = zeros(n+1);
    for i = 2:n
        A(i,i-1) = 1/h;
        A(i,i) = -2/h;
        A(i,i+1) = 1/h;
    end
    
    % Assemble load vector
    b = zeros(n+1,1);
    for i = 2:n
        b(i) = h/2*(f(x(i-1))+f(x(i)));
    end
    
    % Apply boundary conditions
    A(1,:) = 0; A(1,1) = 1; b(1) = 0;
    A(end,:) = 0; A(end,end) = 1; b(end) = 0;
    
    % Solve linear system
    u_num = A\b;
    
    % Visualization comparison
    plot(x,u_num,'r-',x,exact(x),'b--');
    legend('Numerical Solution','Exact Solution');
end

Monte Carlo Simulation Techniques

Random Number Generation and Control

Random Number Generator Configuration:

% Random number seed setting
rng(42);  % Fixed random seed for reproducibility
data1 = rand(1000,1);

rng('shuffle');  % Reset seed based on time
data2 = rand(1000,1);

% Multiple random streams
stream1 = RandStream('mlfg6331_64','Seed',1);
stream2 = RandStream('mrg32k3a','Seed',2);
rand_stream1 = rand(stream1,1000,1);
rand_stream2 = rand(stream2,1000,1);

Advanced Random Distribution Applications:

% Multivariate normal distribution
mu = [1; 2];
Sigma = [1 0.5; 0.5 2];
samples = mvnrnd(mu, Sigma, 1000);

% Poisson process simulation
lambda = 5;
t = cumsum(exprnd(1/lambda, 1, 100));

% Random walk model
steps = randn(1,1000);
walk = cumsum(steps);

Monte Carlo Simulation Cases

Financial Option Pricing:

% European call option pricing
S0 = 100;      % Initial stock price
K = 105;       % Strike price
r = 0.05;      % Risk-free rate
sigma = 0.2;   % Volatility
T = 1;         % Time to maturity
N = 1e5;       % Number of simulations

% Generate random paths
Z = randn(N,1);
ST = S0 * exp((r - 0.5*sigma^2)*T + sigma*sqrt(T)*Z);

% Calculate option payoff
payoff = max(ST - K, 0);
price = exp(-r*T) * mean(payoff);

% Confidence interval calculation
std_err = std(payoff)*exp(-r*T)/sqrt(N);
fprintf('Option price: %.4f ± %.4f\n', price, 1.96*std_err);

Engineering Reliability Analysis:

% Structural system reliability analysis
% Define limit state function
g = @(x) 5 - x(1)^2 - x(2)^2;  % Load-bearing capacity constraint

% Monte Carlo simulation
N = 1e6;
x1 = normrnd(2,0.5,N,1);
x2 = normrnd(3,0.8,N,1);
samples = [x1,x2];
failures = sum(g(samples) < 0);

% Reliability index calculation
pf = failures/N;
COV = sqrt((1-pf)/N/pf);  % Coefficient of variation
fprintf('Failure probability: %.4e, COV: %.4f\n', pf, COV);

Global Optimization Techniques

Genetic Algorithm (ga) Application

Complex Function Optimization:

% Multimodal function optimization
fitnessfcn = @(x) (x(1)^2 + x(2)^2 - 10*cos(2*pi*x(1)) - 10*cos(2*pi*x(2)) + 20);
nvars = 2;
lb = [-5.12; -5.12];
ub = [5.12; 5.12];

% Genetic algorithm configuration
options = optimoptions('ga',...
    'PopulationSize',100,...
    'MaxGenerations',200,...
    'CrossoverFraction',0.8,...
    'MutationFcn',{@mutationadaptfeasible,0.1});

% Execute optimization
[x_ga,fval_ga] = ga(fitnessfcn,nvars,[],[],[],[],lb,ub,[],options);

% Result visualization
[x,y] = meshgrid(linspace(lb(1),ub(1),100),linspace(lb(2),ub(2),100));
z = arrayfun(@(a,b) fitnessfcn([a;b]),x,y);
contour(x,y,z,50);
hold on;
plot(x_ga(1),x_ga(2),'ro','MarkerSize',10);

Constrained Optimization Problem:

% Constrained engineering design optimization
fitnessfcn = @(x) x(1)^2 + x(2)^2 + x(3)^2;  % Objective function (minimize weight)
nvars = 3;
lb = [1;1;1];
ub = [10;10;10];

% Nonlinear constraints
nonlcon = @(x) deal([x(1)*x(2)-10;  % Area constraint
                    x(1)+x(3)-8], []); % Stiffness constraint

% Optimization options
options = optimoptions('ga','Display','iter');

% Execute optimization
[x_ga,fval_ga] = ga(fitnessfcn,nvars,[],[],[],[],lb,ub,nonlcon,options);

Particle Swarm Optimization (particleswarm)

Dynamic System Parameter Identification:

% Model parameter identification problem
fitnessfcn = @(x) sum((simSystem(x) - experimentalData).^2);  % Least squares objective

% Parameter bounds
nvars = 4;  % Number of parameters to identify
lb = [0.1; 0.01; 1; 0.5];  % Lower bounds
ub = [10; 1; 10; 2];       % Upper bounds

% Particle swarm configuration
options = optimoptions('particleswarm',...
    'SwarmSize',50,...
    'MaxIterations',200,...
    'InertiaRange',[0.4 0.9],...
    'SelfAdjustmentWeight',1.4,...
    'SocialAdjustmentWeight',1.4);

% Execute optimization
[x_ps,fval_ps] = particleswarm(fitnessfcn,nvars,lb,ub,options);

% Result verification
estimated_response = simSystem(x_ps);
plot(experimentalData,'b'); hold on;
plot(estimated_response,'r');
legend('Experimental Data','Model Prediction');

Fast Fourier Transform Optimization

FFT Basics and Optimization

Efficient FFT Implementation:

% Signal generation and FFT
fs = 1000;           % Sampling frequency
t = 0:1/fs:1-1/fs;   % Time vector
f1 = 50; f2 = 120;   % Frequency components
x = 0.7*sin(2*pi*f1*t) + sin(2*pi*f2*t);

% Basic FFT computation
N = length(x);
X = fft(x);
f = (0:N-1)*(fs/N);  % Frequency axis

% Magnitude spectrum computation (optimized version)
X_mag = abs(X(1:N/2+1));
X_mag(2:end-1) = 2*X_mag(2:end-1)/N;  % Correct amplitude
plot(f(1:N/2+1), X_mag);
xlabel('Frequency (Hz)'); ylabel('Amplitude');

% Use FFTW optimization
fftw('planner','measure');  % Strategy selection: 'estimate','measure','patient','exhaustive'
X_fast = fft(x);            % Apply optimized FFT algorithm

Spectrum Analysis Optimization:

% Windowed FFT analysis
window = hann(length(x))';  % Hann window
x_windowed = x .* window;

% Spectrum computation
X_windowed = fft(x_windowed);
X_mag_windowed = abs(X_windowed(1:N/2+1));
X_mag_windowed(2:end-1) = 2*X_mag_windowed(2:end-1)/sum(window);

% Spectrum resolution analysis
df = fs/N;  % Frequency resolution
f_resolution = 1/window_length;  % Frequency resolution determined by time window

% Multi-segment averaged PSD
nfft = 2^nextpow2(N);
[pxx,f] = pwelch(x, hann(nfft/8), nfft/16, nfft, fs);
plot(f,10*log10(pxx));
xlabel('Frequency (Hz)'); ylabel('Power Spectral Density (dB/Hz)');

Real-Time FFT Application

Streaming Signal Processing:

% Real-time spectrum analysis system
fs = 1000;           % Sampling rate
window_size = 1024;  % Window size
overlap = 512;       % Overlap points
hop_size = window_size - overlap;

% Initialize buffer
buffer = zeros(window_size,1);
fft_buffer = zeros(window_size,1);

% Create graphical interface
h_fig = figure;
h_line = plot(linspace(0,fs/2,window_size/2+1), zeros(window_size/2+1,1));
xlim([0 fs/2]); ylim([0 1]);
xlabel('Frequency (Hz)'); ylabel('Amplitude');

% Real-time processing loop
while ishandle(h_fig)
    % Acquire new data (simulated)
    new_data = 0.5*sin(2*pi*100*(1:length(buffer))/fs) + 0.2*randn(size(buffer));
    
    % Update buffer (sliding window)
    buffer = [buffer(hop_size+1:end); new_data(1:hop_size)];
    
    % Apply window function
    windowed_data = buffer .* hann(window_size)';
    
    % Compute FFT
    fft_result = fft(windowed_data);
    fft_mag = abs(fft_result(1:window_size/2+1));
    fft_mag(2:end-1) = 2*fft_mag(2:end-1)/sum(hann(window_size));
    
    % Update plot
    set(h_line, 'YData', fft_mag);
    drawnow limitrate;
    
    % Simulate real-time delay
    pause(0.05);
end
Share your love