Skip to content
ME-705 · MATLAB and R Programming/Quick Revision Short Notes

MATLAB and R Programming (ME-705) - Unit 5 Short Notes

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 into m x n grid, activates plot p.

    • Customization: xlabel, ylabel, zlabel, title, legend, axis, grid on.

    • Annotations: text, arrow, doublearrow objects 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) or facet_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. plotly integration 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: TreeBagger for random forests (bagging).

    • SVM: fitcsvm(X,y) for classification/regression.

    • Cross-Validation: cvpartition creates cross-validation partition object for crossval function.

  • 5.2.2 R:

    • Base: lm(y~x1+x2, data) for linear models, glm(y~x, family=binomial, data) for logistic regression.

    • Unified Interface: caret package (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 (fitlm summary, 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) minimizes f'x subject to linear constraints.

    • Global/Genetic: ga (Genetic Algorithm) from Global Optimization Toolbox.

    • Systems: fsolve for solving systems of nonlinear equations F(x)=0.

  • 5.3.2 R:

    • General: optim(par, fn, method="...") (methods: "BFGS", "L-BFGS-B" for bounds, "Nelder-Mead").

    • Nonlinear: nloptr package (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/optim for 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: rng for reproducibility.

  • 5.4.3 R:

    • Efficient Replication: replicate(N, expr) or purrr::rerun(N, expr).

    • Parallel: foreach + doParallel packages 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 (MATLAB histogram, R hist() or ggplot2::geom_histogram()).

5.5 Interoperability & Calling External Code

  • 5.5.1 Calling R from MATLAB:

    • system Command: system('Rscript myscript.R arg1 arg2'). Simple but limited data exchange (files only).

    • MATLAB Engine API for R: (Less common) Requires R package R.matlab on R side to start MATLAB engine.

  • 5.5.2 Calling MATLAB from R:

    • Primary Method: R.matlab package.

      1. library(R.matlab)

      2. matlab <- Matlab() # Start engine

      3. matlab$put("R_var", r_var) # Send R variable to MATLAB

      4. matlab$get("matlab_var") # Retrieve MATLAB variable

      5. matlab$close() # Close engine

    • File-Based: Write data to .mat file from R (writeMat("data.mat", x=r_vec)), read in MATLAB with load('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 viewer to identify bottlenecks.

    • Preallocation: MUST preallocate arrays (A = zeros(N,1)) before loops. Avoids dynamic resizing (O(n²) cost).

    • Vectorization: Replace for loops 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 of for loops. data.table for fast data manipulation (key-based subsetting).

    • Avoid Copies: Be mindful of copy-on-modify behavior. Use data.table or dplyr (with lazy evaluation) for in-place-like operations.

    • Efficient Structures: data.table > dplyr > data.frame for large data.

  • 5.6.3 Memory Management:

    • MATLAB: clear var removes variable. pack (rarely needed) consolidates memory.

    • R: rm(var); gc() forces garbage collection. Use object.size() to check.

5.7 Introduction to GUI Development & Deployment (Conceptual)

  • 5.7.1 MATLAB:

    • App Designer: Modern drag-and-drop environment. Creates .mlapp files. Components (axes, buttons) have properties and callbacks (MATLAB code executed on event).

    • GUIDE: Legacy tool (still supported). Generates .fig and .m files.

    • 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 (or fluidPage()), server logic in server.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, ss for LTI models, pidtuner, bode, step, lsim, lqr, pole/zero placement.

    • 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, modCost for 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., pidtuner for control, bode for 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:

  1. Contrast MATLAB's integrated toolbox approach with R's package ecosystem for modeling (5.2) and optimization (5.3).
  1. Debug/Improve Performance: Identify non-vectorized loops (MATLAB) or for loops with rbind (R). Suggest parfor/foreach or replicate.
  1. Interpret Output: Given fitlm summary or summary(lm), explain p-values, R-squared, coefficients.
  1. Choose Visualization: Given a scenario (e.g., "3D surface of function z=f(x,y)"), select correct function (surf vs. contour vs. geom_contour).
  1. 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.
  1. GUI/Deployment: Distinguish use cases for App Designer (standalone desktop) vs. Shiny (web dashboard).
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in