UNIT 5: ADVANCED APPLICATIONS & INTEROPERABILITY
5.1 Advanced Data Visualization & Graphics
-
5.1.1 MATLAB:
-
3D Plotting:
plot3(x,y,z)for lines,surf(X,Y,Z)for surfaces,mesh(X,Y,Z)for wireframes,contour(X,Y,Z)for level curves. -
Subplots:
subplot(m,n,p)divides figure intom x ngrid, activates plotp. -
Customization:
xlabel,ylabel,zlabel,title,legend,axis,grid on. -
Annotations:
text,arrow,doublearrowobjects for direct figure annotation.
-
-
5.1.2 R:
-
ggplot2 Grammar: Builds plots in layers:
ggplot(data) + geom_point(aes(x,y)) + labs(title="...") + theme_minimal(). -
Faceting:
facet_wrap(~var)orfacet_grid(rowvar ~ colvar)for multi-panel plots. -
Themes:
theme()for non-data ink control (background, fonts). -
Lattice:
xyplot(y~x|group, data)for conditioning plots. -
Interactive:
plotly::ggplotly(p)converts static ggplot to interactive web-based plot.
-
-
5.1.3 Comparative Overview:
-
MATLAB: Excellent for precise, publication-ready static engineering/scientific plots. Integrated, consistent syntax.
-
R (ggplot2): Superior for complex, multi-variable static statistical graphics via layered grammar.
plotlyintegration enables powerful interactive dashboards. -
Key Choice: MATLAB for domain-specific 3D (e.g., topography, CFD); R/ggplot2 for complex statistical relationships and interactive exploration.
-
5.2 Statistical Modeling & Machine Learning (Applied)
-
5.2.1 MATLAB:
-
Toolbox: Statistics and Machine Learning Toolbox.
-
Linear Models:
fitlm(X,y)(linear regression),fitglm(X,y,'Distribution','binomial')(generalized linear). -
Tree Models:
TreeBaggerfor random forests (bagging). -
SVM:
fitcsvm(X,y)for classification/regression. -
Cross-Validation:
cvpartitioncreates cross-validation partition object forcrossvalfunction.
-
-
5.2.2 R:
-
Base:
lm(y~x1+x2, data)for linear models,glm(y~x, family=binomial, data)for logistic regression. -
Unified Interface:
caretpackage (train()) streamlines model training, tuning, and evaluation across 200+ algorithms (e.g.,method="rf",method="svmRadial"). -
Specific Packages:
randomForest::randomForest(),e1071::svm().
-
-
5.2.3 Model Evaluation Metrics:
-
Regression: RMSE = $$\displaystyle \sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2} $$, R-squared.
-
Classification: Accuracy = $$\displaystyle \frac{TP+TN}{Total} $$, ROC-AUC (Area Under ROC Curve).
perfcurve(MATLAB),pROC::roc()(R). -
Interpretation: Examine coefficient significance (
fitlmsummary,summary(lm)), variable importance (TreeBagger.OOBPermutedVarImp,randomForest::importance()).
-
5.3 Optimization & Numerical Methods
-
5.3.1 MATLAB:
-
Unconstrained:
fminsearch(Nelder-Mead simplex),fminunc(quasi-Newton). -
Constrained Nonlinear:
fmincon(sequential quadratic programming). Syntax:[x,fval] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options). -
Linear Programming:
linprog(f,A,b,Aeq,beq,lb,ub)minimizesf'xsubject to linear constraints. -
Global/Genetic:
ga(Genetic Algorithm) from Global Optimization Toolbox. -
Systems:
fsolvefor solving systems of nonlinear equationsF(x)=0.
-
-
5.3.2 R:
-
General:
optim(par, fn, method="...")(methods:"BFGS","L-BFGS-B"for bounds,"Nelder-Mead"). -
Nonlinear:
nloptrpackage (interface to NLopt library) for advanced constraints/algorithms. -
Linear Programming:
lpSolve::lp(direction="min", objective.in, const.mat, const.dir, const.rhs).
-
-
5.3.3 Application Examples:
-
Parameter Fitting: Minimize sum of squared errors between model and data.
-
Resource Allocation: Linear programming for cost minimization under constraints.
-
Engineering Design:
fmincon/optimfor shape/topology optimization with stress/deflection constraints.
-
5.4 Simulation & Monte Carlo Methods
-
5.4.1 Core Idea: Use random sampling to estimate complex system behavior or probabilistic quantities.
-
5.4.2 MATLAB:
-
Vectorization: Pre-generate all random numbers at once (e.g.,
results = arrayfun(@(i) mySim(i), 1:N)or direct matrix ops). Critical for speed. -
Parallel Loops:
parfor(Parallel Computing Toolbox) for independent replications. -
Random Streams:
rngfor reproducibility.
-
-
5.4.3 R:
-
Efficient Replication:
replicate(N, expr)orpurrr::rerun(N, expr). -
Parallel:
foreach+doParallelpackages for parallel loops. -
Vectorization: Use built-in vectorized functions (
rnorm(N),sample(..., N, replace=TRUE)).
-
-
5.4.4 Output Analysis:
-
Compute sample mean, standard error ($$\displaystyle SE = s/\sqrt{n} $$), and confidence intervals (e.g., $$\displaystyle \bar{x} \pm t_{\alpha/2, n-1} \cdot SE $$).
-
Visualize with
histogram(MATLABhistogram, Rhist()orggplot2::geom_histogram()).
-
5.5 Interoperability & Calling External Code
-
5.5.1 Calling R from MATLAB:
-
systemCommand:system('Rscript myscript.R arg1 arg2'). Simple but limited data exchange (files only). -
MATLAB Engine API for R: (Less common) Requires R package
R.matlabon R side to start MATLAB engine.
-
-
5.5.2 Calling MATLAB from R:
-
Primary Method:
R.matlabpackage.-
library(R.matlab) -
matlab <- Matlab()# Start engine -
matlab$put("R_var", r_var)# Send R variable to MATLAB -
matlab$get("matlab_var")# Retrieve MATLAB variable -
matlab$close()# Close engine
-
-
File-Based: Write data to
.matfile from R (writeMat("data.mat", x=r_vec)), read in MATLAB withload('data.mat').
-
-
5.5.3 Data Exchange Formats:
-
CSV: Universal, text-based.
csvwrite(MATLAB),write.csv(R). Loss of metadata. -
HDF5: Hierarchical, efficient for large datasets.
h5write/h5read(MATLAB),rhdf5(R). -
Native:
.mat(MATLAB),.RData/.rds(R). Use only when workflow is primarily in one environment.
-
5.6 Performance Tuning & Best Practices
-
5.6.1 MATLAB:
-
Profiling:
profile on-> run code ->profile viewerto identify bottlenecks. -
Preallocation: MUST preallocate arrays (
A = zeros(N,1)) before loops. Avoids dynamic resizing (O(n²) cost). -
Vectorization: Replace
forloops with matrix/array operations. Big O improvement often from O(n) to O(1) per element. -
Timing:
tic; code; toc.
-
-
5.6.2 R:
-
Profiling:
Rprof("profile.out")-> run code ->summaryRprof("profile.out"). -
Vectorization & Apply Family: Use
apply(X, MARGIN, FUN),sapply(),lapply()instead offorloops.data.tablefor fast data manipulation (key-based subsetting). -
Avoid Copies: Be mindful of copy-on-modify behavior. Use
data.tableordplyr(with lazy evaluation) for in-place-like operations. -
Efficient Structures:
data.table>dplyr>data.framefor large data.
-
-
5.6.3 Memory Management:
-
MATLAB:
clear varremoves variable.pack(rarely needed) consolidates memory. -
R:
rm(var); gc()forces garbage collection. Useobject.size()to check.
-
5.7 Introduction to GUI Development & Deployment (Conceptual)
-
5.7.1 MATLAB:
-
App Designer: Modern drag-and-drop environment. Creates
.mlappfiles. Components (axes, buttons) have properties and callbacks (MATLAB code executed on event). -
GUIDE: Legacy tool (still supported). Generates
.figand.mfiles. -
Deployment: Compile apps to standalone executables (.exe) using MATLAB Compiler (requires MATLAB Runtime).
-
-
5.7.2 R:
-
Shiny: Web application framework. UI defined in
ui.R(orfluidPage()), server logic inserver.R. Reactive programming (reactive(),renderPlot()) updates outputs automatically when inputs change. -
Deployment: Apps run locally or deployed to shinyapps.io or on-premise Shiny Server.
-
-
5.7.3 Comparison:
-
MATLAB App Designer: Best for standalone desktop tools for engineers/scientists already in MATLAB ecosystem. Tight integration with MATLAB graphics and toolboxes.
-
R Shiny: Best for web-based dashboards and interactive data exploration accessible via browser. Leverages R's statistical/graphical power (ggplot2, plotly) for dynamic reports.
-
5.8 Specialized Toolboxes/Packages for Engineering (Survey)
-
5.8.1 MATLAB:
-
Signal Processing Toolbox: Filter design (
fdesign,designfilt), spectral analysis (periodogram,pwelch), waveform generation. -
Control System Toolbox:
tf,ssfor LTI models,pidtuner,bode,step,lsim,lqr,pole/zeroplacement. -
Simulink: Graphical multi-domain simulation and model-based design. Block diagrams for dynamic systems. Generates C code.
-
-
5.8.2 R:
-
signal:
filter,fft,spec.pgram(similar to MATLAB Signal Processing Toolbox). -
pracma: Practical math functions—
polyval,interp1,ode45(numerical integration),expm(matrix exponential). -
FME (Flexible Modeling Environment):
modFit,modCostfor model fitting and sensitivity analysis (similar to MATLAB's System Identification/Simulink Design Optimization).
-
-
5.8.3 Choosing the Right Tool:
-
Use Specialized Toolbox/Package: When domain-specific functions are available, validated, and optimized (e.g.,
pidtunerfor control,bodefor frequency response). Saves development time and reduces errors. -
Write Custom Code: When problem is unique, requires specific algorithm not in toolbox, or for maximum transparency/educational purposes. Weigh development time vs. toolbox licensing/availability.
-
UNIT 5 EXAM FOCUS SUMMARY:
- Contrast MATLAB's integrated toolbox approach with R's package ecosystem for modeling (5.2) and optimization (5.3).
- Debug/Improve Performance: Identify non-vectorized loops (MATLAB) or
forloops withrbind(R). Suggestparfor/foreachorreplicate.
- Interpret Output: Given
fitlmsummary orsummary(lm), explain p-values, R-squared, coefficients.
- Choose Visualization: Given a scenario (e.g., "3D surface of function z=f(x,y)"), select correct function (
surfvs.contourvs.geom_contour).
- Interoperability: Sketch steps to pass a data frame from R to MATLAB for a specific toolbox function (e.g.,
fitcsvm). Answer: Export to CSV/MAT, load in other environment.
- GUI/Deployment: Distinguish use cases for App Designer (standalone desktop) vs. Shiny (web dashboard).