Lesson 21-MATLAB Scientific Computing and Engineering Simulation

Scientific Computing and Engineering Simulation

Numerical Simulation Techniques

Fluid Dynamics and Heat Conduction Simulation:

% 1. Fluid dynamics simulation (based on Navier-Stokes equations)
% Solve 2D steady-state flow using PDE Toolbox
model = createpde(2);  % 2D problem
geometryFromEdges(model,@lshapeg);  % L-shaped geometry
applyBoundaryCondition(model,'dirichlet','Edge',1:4,'u',[0 0]);  % No-slip boundary
specifyCoefficients(model,'m',0,'d',0,'c',1e-3,'a',0,'f',0);  % Viscous fluid parameters
generateMesh(model,'Hmax',0.1);  % Mesh generation
results = solvepde(model);  % Solve
pdeplot(model,'XYData',results.NodalSolution(:,1));  # x-direction velocity field

% 2. Heat conduction simulation
model = createpde(1);  % 1D heat conduction
geometryFromEdges(model,@squareg);  # Square region
applyBoundaryCondition(model,'dirichlet','Edge',1,'u',100);  # Left boundary temperature 100
applyBoundaryCondition(model,'neumann','Edge',2:4,'g',0);  # Adiabatic boundary
specifyCoefficients(model,'m',0,'d',1,'c',1,'a',0,'f',0);  # Heat conduction parameters
generateMesh(model);
thermalResults = solvepde(model);
pdeplot(model,'XYData',thermalResults.NodalSolution);  % Temperature distribution

Finite Element and Finite Difference Methods

Structural Mechanics FEA Analysis:

% 1. Finite element analysis (beam structure)
model = createpde('structural','static-planestress');
geometryFromEdges(model,@cantileverg);  % Cantilever beam geometry
applyBoundaryCondition(model,'fixed','Edge',4);  # Fixed end constraint
applyBoundaryCondition(model,'force','Edge',2,'Fy',-1e3);  # End load
generateMesh(model,'Hmax',0.05);
structuralResults = solve(model);
pdeplot(model,'XYData',structuralResults.Displacement.uy,'Deformation',structuralResults.Displacement);
title('Beam Deflection Distribution');

% 2. Finite difference method (FDM) for solving PDEs
% Numerical solution of 2D heat conduction equation
Nx = 50; Ny = 50;  % Grid points
Lx = 1; Ly = 1;    % Domain size
dx = Lx/(Nx-1); dy = Ly/(Ny-1);
x = linspace(0,Lx,Nx); y = linspace(0,Ly,Ny);
[X,Y] = meshgrid(x,y);

% Initial and boundary conditions
T = zeros(Ny,Nx);
T(1,:) = 100;  % Top boundary temperature 100
T(end,:) = 50; % Bottom boundary temperature 50
T(:,1) = 75;   % Left boundary temperature 75
T(:,end) = 25; % Right boundary temperature 25

% Iterative solution
alpha = 1e-4;  % Thermal diffusivity
dt = 0.1;      % Time step
maxIter = 1000;
for n = 1:maxIter
    Tnew = T;
    for i = 2:Ny-1
        for j = 2:Nx-1
            Tnew(i,j) = T(i,j) + alpha*dt*(...
                (T(i+1,j)-2*T(i,j)+T(i-1,j))/dy^2 + ...
                (T(i,j+1)-2*T(i,j)+T(i,j-1))/dx^2);
        end
    end
    T = Tnew;
end
surf(X,Y,T); xlabel('x'); ylabel('y'); zlabel('Temperature');

Control System Design

PID and State-Space Models:

% 1. PID controller design and simulation
plant = tf(1,[1 2 1]);  % Second-order system
pidCtrl = pidtuner(plant,'PID');
pidCtrl.TuneMethod = 'automatic';
pidCtrl.OptimizeFor = 'disturbance-rejection';
pidCtrl.Tune;
closedLoop = feedback(pidCtrl.Output,plant);
step(closedLoop); title('PID Control Step Response');

% 2. State-space model design and simulation
A = [-1 2; -0.5 -3];
B = [1; 0.5];
C = [1 0];
D = 0;
sys_ss = ss(A,B,C,D);

% State feedback controller design
K = place(A,B,[ -2 -3 ]);  % Pole placement
sys_cl = ss(A-B*K,B,C,D);
step(sys_cl); title('State Feedback Control Response');

% 3. LQR optimal control
Q = diag([10 1]);  % State weighting
R = 0.1;           % Control input weighting
[K_lqr,S,e] = lqr(A,B,Q,R);
sys_lqr = ss(A-B*K_lqr,B,C,D);
step(sys_lqr); title('LQR Control Response');

Signal Processing Simulation

Communication System Modeling:

% 1. Digital communication system simulation
% Generate random binary data
data = randi([0 1],1,1000);

% BPSK modulation
modulated = pskmod(data,2);

% AWGN channel
SNR = 10;  % Signal-to-noise ratio (dB)
received = awgn(modulated,SNR,'measured');

% Demodulation and BER calculation
demodulated = pskdemod(received,2);
[~,ber] = biterr(data,demodulated);
fprintf('BER: %.4f\n', ber);

% 2. Filter design and application
Fs = 1e3;  % Sampling rate
Fpass = 100;  % Passband cutoff frequency
Fstop = 150;  % Stopband cutoff frequency
d = designfilt('lowpassfir','PassbandFrequency',Fpass,...
    'StopbandFrequency',Fstop,'SampleRate',Fs);
t = 0:1/Fs:1-1/Fs;
x = sin(2*pi*50*t) + 0.5*sin(2*pi*200*t);
y = filter(d,x);
subplot(2,1,1); plot(t,x); title('Original Signal');
subplot(2,1,2); plot(t,y); title('Filtered Signal');

Image Processing Applications

Computer Vision Algorithms:

% 1. Image segmentation and feature extraction
I = imread('coins.png');
bw = imbinarize(I);  % Binarization
stats = regionprops(bw,'Area','Centroid','BoundingBox');

% Display segmentation results
figure;
imshow(I); hold on;
for k = 1:length(stats)
    rectangle('Position',stats(k).BoundingBox,...
        'EdgeColor','r','LineWidth',2);
    plot(stats(k).Centroid(1),stats(k).Centroid(2),'g*');
end
title('Coin Segmentation and Feature Extraction');

% 2. Object detection (template matching)
template = imread('template.png');
I = imread('scene.png');
correlation = normxcorr2(template(:,:,1), I(:,:,1));
[y,x] = find(correlation == max(correlation(:)));
figure;
imshow(I); hold on;
rectangle('Position',[x,y,size(template,2),size(template,1)],...
    'EdgeColor','r','LineWidth',2);
title('Object Detection Result');

% 3. Optical flow motion estimation
video = VideoReader('traffic.avi');
reader = vision.VideoFileReader('traffic.avi');
motionEstimator = vision.OpticalFlow('OutputValue','Horizontal and vertical components');
while ~isDone(reader)
    frame = step(reader);
    flow = step(motionEstimator,frame);
    imshow(frame); hold on;
    quiver(flow(:,:,1),flow(:,:,2));  % Draw optical flow vectors
    pause(0.01);
end

Data Science and Artificial Intelligence

Data Mining and Prediction

Time Series Analysis and Regression:

% 1. Time series forecasting (ARIMA model)
load('Data_Airline.mat');  % Airline passenger data
ts = timeseries(Data,AirlineDates);
plot(ts); title('Airline Passenger Time Series');

% ARIMA model fitting
model = arima(0,1,1);  % ARIMA(p,d,q)
estModel = estimate(model,Data');
[yF,yMSE] = forecast(estModel,24,'Y0',Data');
upper = yF + 1.96*sqrt(yMSE);
lower = yF - 1.96*sqrt(yMSE);

% Forecast visualization
figure;
plot(Data,'b'); hold on;
plot(length(Data)+1:length(Data)+24,yF,'r','LineWidth',2);
plot(length(Data)+1:length(Data)+24,upper,'k--');
plot(length(Data)+1:length(Data)+24,lower,'k--');
title('Airline Passenger Forecast (ARIMA)');

% 2. Regression analysis (multiple linear regression)
load carsmall
X = [Horsepower Weight Acceleration];
y = MPG;
mdl = fitlm(X,y);
disp(mdl);
plotSlice(mdl);  % Interactive slice plot

Machine Learning Model Development

Classification and Clustering Systems:

% 1. Classification model (random forest)
load fisheriris
X = meas;
Y = species;

% Train random forest
mdl = TreeBagger(100,X,Y,'Method','classification');
[Y_pred, scores] = predict(mdl,X);

% Evaluate model
confMat = confusionmat(categorical(Y), categorical(Y_pred));
figure;
confusionchart(categorical(Y), categorical(Y_pred));
title('Random Forest Classification Results');

% 2. Clustering analysis (K-means)
X = [randn(100,2)+ones(100,2); randn(100,2)-ones(100,2)];
[idx, C] = kmeans(X,2);

% Visualize clustering results
figure;
gscatter(X(:,1),X(:,2),idx);
hold on;
plot(C(:,1),C(:,2),'kx','MarkerSize',15);
title('K-means Clustering Results');

% 3. Recommendation system (collaborative filtering)
load movieLensDataset
% Create rating matrix
ratingMatrix = sparse(userRatingData(:,1), userRatingData(:,2), userRatingData(:,3));
% Train recommendation model
recModel = recommender('als',ratingMatrix);
% Recommend for user
userID = 10;
numRecs = 5;
[recItems, scores] = recommend(recModel, userID, numRecs);

Deep Learning Models

Image and Object Detection:

% 1. Image classification (CNN)
% Load pre-trained network
net = resnet50;
% Replace classification layer
numClasses = 10;  % Custom number of classes
newLayers = [ ...
    fullyConnectedLayer(numClasses,'Name','fc_new')
    softmaxLayer('Name','softmax_new')
    classificationLayer('Name','output_new')];
lgraph = layerGraph(net);
lgraph = replaceLayer(lgraph,'fc1000',newLayers(1));
lgraph = replaceLayer(lgraph,'ClassificationLayer_fc1000',newLayers(3));

% Prepare training data
augimds = augmentedImageDatastore([224 224 3],imdsTrain);
% Train network
options = trainingOptions('adam',...
    'MaxEpochs',10,...
    'MiniBatchSize',32,...
    'ValidationData',augimdsValidation,...
    'Plots','training-progress');
net = trainNetwork(augimds,lgraph,options);

% 2. Object detection (Faster R-CNN)
% Load pre-trained vehicle detector
detector = vehicleDetectorFasterRNN;
% Detect vehicles in image
I = imread('highway.png');
[bboxes, scores, labels] = detect(detector,I);
% Visualize results
annotatedImage = insertObjectAnnotation(I,'rectangle',bboxes,labels);
figure;
imshow(annotatedImage);
title('Vehicle Detection Results');

Natural Language Processing

Text Analysis and Sentiment Analysis:

% 1. Text classification (word embedding)
% Load pre-trained word vectors
emb = fastTextWordEmbedding;
% Document tokenization
documents = tokenizedDocument([
    'MATLAB is a high-level programming language'
    'Deep learning requires GPU acceleration'
    'Statistical analysis is important in research'
]);
% Convert to word vector sequences
sequence = doc2sequence(emb,documents);
% Train classifier
Y = categorical([1 2 1]);  % Example labels
numHiddenUnits = 200;
layers = [ ...
    sequenceInputLayer(size(emb,2))
    bilstmLayer(numHiddenUnits,'OutputMode','last')
    fullyConnectedLayer(numClasses=2)
    softmaxLayer
    classificationLayer];
options = trainingOptions('adam',...
    'MaxEpochs',10,...
    'MiniBatchSize',1);
net = trainNetwork(sequence,Y,layers,options);

% 2. Sentiment analysis
% Load pre-trained sentiment analysis model
sentimentNet = alexnet;  % Should use dedicated text network in practice
% Text preprocessing (simplified example here)
textData = {'I love MATLAB','This is terrible'};
% Convert to model input format (requires custom preprocessing)
% predictions = classify(sentimentNet,processedText);

Reinforcement Learning Systems

Intelligent Decision-Making and Control:

% 1. Q-learning algorithm implementation
% Define environment (grid world)
gridWorld = GridWorldEnvironment;
numStates = gridWorld.getNumStates;
numActions = gridWorld.getNumActions;

% Initialize Q-table
QTable = zeros(numStates,numActions);

% Learning parameters
gamma = 0.9;  % Discount factor
alpha = 0.1;  % Learning rate
epsilon = 0.1; % Exploration rate

% Training loop
for episode = 1:1000
    state = gridWorld.reset;
    done = false;
    
    while ~done
        % ε-greedy policy to select action
        if rand < epsilon
            action = randi(numActions);
        else
            action = find(QTable(state,:) == max(QTable(state,:)),1);
        end
        
        % Execute action
        [nextState, reward, done] = gridWorld.step(action);
        
        % Q-value update
        QTable(state,action) = QTable(state,action) + ...
            alpha*(reward + gamma*max(QTable(nextState,:)) - QTable(state,action));
        
        state = nextState;
    end
end

% 2. Deep Q-Network (DQN)
% Define network architecture
layers = [ ...
    featureInputLayer(gridWorld.getNumObservations)
    fullyConnectedLayer(128)
    reluLayer()
    fullyConnectedLayer(128)
    reluLayer()
    fullyConnectedLayer(numActions)];

% Training options
options = trainingOptions('adam',...
    'MaxEpochs',100,...
    'MiniBatchSize',64,...
    'GradientThreshold',1);

% Create DQN agent
agent = dqnAgent(gridWorld,layers,options);

% Train agent
trainStats = train(agent,gridWorld,'MaxSteps',10000);

% 3. Policy evaluation
initialState = gridWorld.reset;
done = false;
totalReward = 0;

while ~done
    action = getAction(agent,initialState);
    [nextState, reward, done] = gridWorld.step(action);
    totalReward = totalReward + reward;
    initialState = nextState;
end

fprintf('Test episode total reward: %.2f\n',totalReward);

Cross-Platform and Embedded Development

Embedded System Integration

Code Generation and Deployment:

% 1. PID controller code generation
plant = tf(1,[1 2 1]);  % Second-order system
pidCtrl = pidtuner(plant,'PID');
pidCtrl.Tune;
pidCtrl.Output;

% Generate C code
slbuild(pidCtrl);  % Generate Simulink model code
% Or generate standalone code directly
codegen('-config','lib','-args',{0,0,0},'pidController','-report');

% 2. Motor control algorithm deployment
model = 'motorControlSystem';
open_system(model);
% Configure code generation parameters
cfg = coder.config('lib');
cfg.TargetLang = 'C';
cfg.HardwareImplementation.ProdHWDeviceType = 'ARM Compatible->ARM Cortex';
cfg.CodePlacement = 'Auto';
% Generate code
codegen('-config',cfg,'motorControlAlgorithm','-args',{0,0,0});

% 3. Real-time system code optimization
% Use Fixed-Point Designer for fixed-point quantization
fp = fipref('NumberDisplay','RealWorldValue',...
    'NumericTypeDisplay','short',...
    'LoggingMode','on');
a = fi(pi,1,16,14);  % 16-bit fixed-point, 14 fractional bits
b = fi(exp(1),1,16,14);
c = a * b;  % Fixed-point multiplication

Cross-Platform Application Development

Multi-Platform GUI Design:

% 1. App Designer cross-platform application
function createCrossPlatformApp()
    app = uifigure('Name','Cross-Platform Data Analysis Tool','Position',[100 100 800 600]);
    
    % Add data selection component
    uibutton(app,'Text','Load Data','Position',[50 500 100 30],...
        'ButtonPushedFcn',@loadData);
    
    % Add analysis options
    uibutton(app,'Text','Run Analysis','Position',[200 500 100 30],...
        'ButtonPushedFcn',@runAnalysis);
    
    % Add result display area
    app.UIAxes = uiaxes(app,'Position',[50 100 700 350]);
    
    % Store application data
    app.Data = [];
end

function loadData(app,event)
    [file,path] = uigetfile({'*.mat','MAT Files';'*.csv','CSV Files'});
    if isequal(file,0)
        return;
    end
    [~,~,ext] = fileparts(file);
    if strcmpi(ext,'.mat')
        app.Data = load(fullfile(path,file));
    else
        app.Data = readtable(fullfile(path,file));
    end
    msgbox('Data loaded successfully!');
end

function runAnalysis(app,event)
    if isempty(app.Data)
        errordlg('Please load data first!');
        return;
    end
    % Perform analysis (example: plot data)
    if istable(app.Data)
        plot(app.UIAxes,app.Data{:,1},app.Data{:,2});
    else
        plot(app.UIAxes,app.Data);
    end
    title(app.UIAxes,'Data Analysis Results');
end

% 2. Deploy as standalone application
% Using MATLAB Compiler
compiler.build.standaloneApplication('createCrossPlatformApp.m',...
    'AppName','DataAnalyzer',...
    'OutputDir','deploy');

Web Application Integration

MATLAB Production Server Deployment:

% 1. Create web service function
function [prediction, confidence] = predictStockPrice(inputData)
    % Load pre-trained model
    persistent model
    if isempty(model)
        model = load('stockModel.mat','net');
    end
    
    % Data preprocessing
    processedData = preprocessInput(inputData);
    
    % Model prediction
    [prediction, scores] = predict(model.net, processedData);
    confidence = max(scores);
end

% 2. Compile as web service
compiler.build.productionServerDeployment('predictStockPrice.m',...
    'ServiceName','StockPrediction',...
    'OutputDir','web_deploy');

% 3. Generate Swagger documentation
compiler.build.productionServerSwagger('predictStockPrice.m',...
    'OutputDir','api_docs');

% 4. Client call example (MATLAB)
url = 'http://server.example.com/StockPrediction';
inputData = struct('Open',150.2,'High',155.7,'Low',149.8,'Volume',1e6);
options = weboptions('ContentType','application/json');
response = webwrite(url,inputData,options);
prediction = jsondecode(response).prediction;

% Python client call example
"""
import requests
import json

url = "http://server.example.com/StockPrediction"
data = {"Open":150.2,"High":155.7,"Low":149.8,"Volume":1e6}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
prediction = response.json()['prediction']
"""

Mobile Application Development

MATLAB Mobile Integration:

% 1. Create mobile-compatible algorithm
function [filteredData] = mobileSignalProcessing(rawData)
    % Lightweight filter design (suitable for mobile devices)
    b = [0.2 0.2 0.2 0.2 0.2];  % Simple moving average filter
    a = 1;
    filteredData = filter(b,a,rawData);
end

% 2. Deploy to MATLAB Mobile
% Use MATLAB Coder to generate C code
codegen('-config','lib','-args',{randn(100,1)},'mobileSignalProcessing','-report');

% 3. Run on mobile device
% Connect via MATLAB Mobile to server
% Run pre-deployed algorithm

% 4. Real-time data acquisition example
function collectAndProcess()
    % Simulate sensor data acquisition
    t = 0:0.01:10;
    rawData = sin(2*pi*1*t) + 0.5*randn(size(t));
    
    % Process data
    filteredData = mobileSignalProcessing(rawData);
    
    % Visualize results (on mobile device)
    plot(t,rawData,'b',t,filteredData,'r');
    legend('Raw Data','Filtered Data');
    title('Mobile Signal Processing Demo');
end

Real-Time System Development

Hardware-in-the-Loop Simulation:

% 1. Speedgoat hardware-in-the-loop configuration
% Create real-time model
model = 'realTimeControlSystem';
open_system(model);

% Configure model parameters
set_param(model,'SimulationMode','external');
set_param(model,'FixedStep','0.001');  % 1ms step size

% 2. Target machine connection and deployment
tg = slrealtime('TargetPC1');
connect(tg);

% Add I/O modules
addBlock('slrealtime/IO/Analog Input','model/AI_Sensor');
set_param('model/AI_Sensor','Channel','0','SampleTime','0.001');

addBlock('slrealtime/IO/Digital Output','model/DO_Control');
set_param('model/DO_Control','Channel','1','SampleTime','0.001');

% Download model to target machine
tg.download(model);

% 3. Real-time control algorithm implementation
% Use Stateflow in model for state machine
% Or write S-Function for low-level control

% 4. Data logging and analysis
tg.start;
pause(10);  % Run for 10 seconds
tg.stop;

% Retrieve logged data
data = tg.getLoggedData;
plot(data.Time,data.Data);
title('Real-Time System Response');

% 5. Performance optimization
% Use Rapid Accelerator mode to speed up simulation
set_param(model,'SimulationMode','rapid');
simOut = sim(model,'SimulationMode','rapid');
Share your love