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

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

3.1 Advanced Data Structures & Manipulation (Both Languages)

3.1.1 Complex Data Types & Structures

  • MATLAB:

    • Cell Arrays: C = {1, 'text', [1 2 3]}; heterogeneous data, accessed with curly braces {}.

    • Structures: S.name = 'Alice'; S.age = 30;; fields accessed via dot ..

    • Tables: T = table(var1, var2, ...); column-oriented, ideal for heterogeneous tabular data. Row/column names accessible.

    • Timetables: TT = timetable(t, var1, var2, ...); table with row times as datetime; time-based indexing/alignment.

    • Categorical Arrays: cat = categorical({'Low','Medium','High'}); memory-efficient for discrete non-numeric data.

  • R:

    • Lists: L <- list(a=1, b="text", c=c(1,2,3)); heterogeneous, accessed via $ or [[ ]].

    • Factors: f <- factor(c("Low","Medium","High")); categorical data with levels; crucial for modeling.

    • Data Frames: df <- data.frame(col1, col2); list of equal-length vectors; primary tabular structure.

    • Tibbles: tb <- tibble(col1, col2); modern re-imagining (tidyverse); never changes input types, prints nicely.

    • Matrices: m <- matrix(1:9, nrow=3); homogeneous, 2D; atomic vectors only.

[!TIP] Key Difference: MATLAB table is analogous to R data.frame/tibble but with stronger time-series support via timetable. R factors are explicit; MATLAB uses categorical.

3.1.2 Data Import/Export & I/O Operations

Format MATLAB Functions R Functions (tidyverse)
CSV readtable('file.csv'), writetable(T, 'file.csv') readr::read_csv(), readr::write_csv()
Excel readtable('file.xlsx'), writetable(T, 'file.xlsx') readxl::read_excel(), writexl::write_xlsx()
Text readtable('file.txt') (with Delimiter), textscan readr::read_delim()
JSON jsondecode(jsonStr), jsonencode(struct) jsonlite::fromJSON(), jsonlite::toJSON()
MAT-file load('file.mat'), save('file.mat', 'var') R.matlab::readMat(), R.matlab::writeMat()

3.1.3 Data Cleaning & Transformation Pipelines

  • Missing Data:

    • MATLAB: rmmissing(T) (remove rows), fillmissing(T, 'constant', 0) (impute).

    • R: tidyr::drop_na(), tidyr::replace_na(); dplyr::filter(!is.na(col)).

  • Reshaping:

    • Wide to Long: MATLAB: stack(T); R: tidyr::pivot_longer(df, cols = c(col1, col2), names_to = "var", values_to = "val").

    • Long to Wide: MATLAB: unstack(T, 'values', 'variable'); R: tidyr::pivot_wider(df, names_from = "var", values_from = "val").

  • Pipeline Concept:

    • MATLAB: Nested function calls or rowfun/varfun. No native pipe operator (use %>% from tidyverse in R).

    • R: %>% pipe from magrittr/dplyr enables left-to-right readable pipelines: df %>% filter(x>0) %>% mutate(y = log(x)).

[!TIP] Common Pitfall: In MATLAB, table operations often require specifying VariableNames. In R, dplyr verbs return tibbles by default; use as.data.frame() for base R functions.


3.2 Advanced Visualization & Graphics

3.2.1 MATLAB Graphics System Deep Dive

  • Handle Graphics: All plots are objects (e.g., line, axes, figure). Get handle: h = plot(x,y). Modify: h.LineWidth = 2; h.Color = 'r'.

  • Customization:

    • Axes: ax = gca; ax.XLabel.String = 'Time'; ax.FontSize = 12;.

    • Legends: legend({'Data1','Data2'}, 'Location', 'northwest').

    • Colormaps: colormap(jet), caxis([min max]).

  • Subplots:

    • subplot(m,n,p) – older, creates axes in a grid.

    • tiledlayout(m,n) – newer, better control; use nexttile for each plot. Preferred for complex layouts.

  • Interactive Tools: zoom on, pan on, datacursormode on (click to inspect data points).

3.2.2 R's Grammar of Graphics (ggplot2)

  • Core Philosophy: Build plots by adding layers to a base ggplot object.

  • Basic Template:

    
    ggplot(data = df, mapping = aes(x = var1, y = var2, color = group)) +
    
      geom_point() +      # Layer 1: Points
    
      geom_smooth(method = "lm") + # Layer 2: Trend line
    
      facet_wrap(~category) + # Layer 3: Small multiples
    
      labs(title = "Plot", x = "X Label") +
    
      theme_minimal()
    
    
  • Key Components:

    • ggplot(): Initialize with data & global aesthetics (aes()).

    • Geoms: geom_point(), geom_line(), geom_bar(), geom_histogram().

    • Facets: facet_grid(row ~ col) or facet_wrap(~ var) for multi-panel plots.

    • Scales: scale_x_log10(), scale_color_manual(values = c('red','blue')).

    • Themes: theme_bw(), theme_minimal(); customize with theme().

3.2.3 Specialized & Interactive Plots

  • MATLAB:

    • 3D: surf(X,Y,Z), mesh(X,Y,Z), contour3(X,Y,Z).

    • Geographic: geoplot(lat,lon), geoscatter(lat,lon) (Mapping Toolbox).

    • Animation: Capture frames with F(i) = getframe(gcf); then movie(F).

  • R:

    • Interactive: plotly::ggplotly(p) converts ggplot to interactive web plot.

    • Dashboards: shiny app structure: ui <- fluidPage(...); server <- function(input, output) {...}; shinyApp(ui, server).

[!TIP] ggplot2 vs MATLAB: ggplot2's layered grammar is declarative and consistent; MATLAB is imperative (modify objects after creation). ggplot2 excels at complex multi-variable plots; MATLAB excels at programmatic 3D/engineering visualizations.


3.3 Statistical Modeling & Machine Learning Foundations

3.3.1 Inferential Statistics & Hypothesis Testing

  • Parametric vs. Non-Parametric:

    • Parametric: Assumes population distribution (e.g., normal). More powerful if assumptions hold.

    • Non-Parametric: Fewer assumptions; used for ordinal data or non-normal distributions.

  • Common Tests:

    | Test | Purpose | MATLAB Function | R Function | | :--- | :--- | :--- | :--- | | t-test | Compare means (1/2 samples) | ttest(x, mu) or ttest2(x,y) | t.test(x, mu) or t.test(x,y) | | ANOVA | Compare >2 group means | anova1(data, group) | aov(response ~ group, data=df) | | Chi-square| Test independence (categorical) | chi2gof(data) or crosstab | chisq.test(table) | | Correlation| Linear/rank relationship | [r,p] = corr(x,y,'Type','Pearson') | cor.test(x,y, method='pearson') |

3.3.2 Regression Analysis

  • Linear Regression:

    • Model: $$\displaystyle y = \beta_0 + \beta_1 x_1 + ... + \beta_p x_p + \epsilon $$, where $$\displaystyle \epsilon \sim N(0, \sigma^2) $$.

    • Fitting:

      • MATLAB: mdl = fitlm(X, y); stepwiselm for variable selection.

      • R: mdl <- lm(y ~ x1 + x2, data=df).

    • Diagnostics: Check residuals (mdl.Residuals.Raw in MATLAB; residuals(mdl) in R) for normality, homoscedasticity. R-squared: mdl.Rsquared.Ordinary (MATLAB); summary(mdl)$r.squared (R).

  • Logistic Regression (Binary Classification):

    • Model: $$\displaystyle \log\left(\frac{p}{1-p}\right) = \beta_0 + \beta_1 x_1 + ... $$, where $$\displaystyle p = P(Y=1|X) $$.

    • Fitting:

      • MATLAB: mdl = fitglm(X, y, 'Distribution', 'binomial').

      • R: mdl <- glm(y ~ x1 + x2, family=binomial, data=df).

    • Output: Coefficients are log-odds ratios. Convert via $$\displaystyle \text{odds} = e^{\beta} $$.

3.3.3 Introduction to Machine Learning Toolboxes

  • MATLAB (Statistics and Machine Learning Toolbox):

    • Classification: fitcsvm (Support Vector Machine), fitctree (Decision Tree), fitcnb (Naive Bayes).

    • Clustering: kmeans (k-means), cluster (hierarchical).

    • Workflow: fit -> predict -> loss (evaluate).

  • R:

    • caret package: Unified interface (train()) for 200+ models. Handles preprocessing, cross-validation.

    • tidymodels: Modern, modular framework (parsnip for models, recipes for preprocessing, workflows for pipelines).

    • Example: library(tidymodels); model <- logistic_reg() %>% set_engine('glm') %>% fit(y~., data=train).

[!TIP] Exam Focus: Know the function names for basic models in both environments. Understand that logistic regression outputs log-odds; interpret coefficients accordingly. Always validate models with a hold-out/test set.


3.4 Performance, Debugging & Best Practices

3.4.1 Code Optimization & Profiling

  • Profiling:

    • MATLAB: profile on; myFunc(); profile viewer – shows time per line/function.

    • R: profvis::profvis({ myFunc() }) – interactive flame graph.

  • Key Optimization Techniques:

    • Vectorization: Replace for loops with matrix/array operations.

      • MATLAB: y = A * x vs. looping.

      • R: df$$\displaystyle newCol <- df $$col1 * df$col2 vs. for loop.

    • Preallocation: Allocate memory before loops.

      • MATLAB: A = zeros(1000,1000);

      • R: vec <- numeric(1000) or vec <- vector("numeric", 1000).

    • Parallel Loops (MATLAB): parfor (requires Parallel Computing Toolbox) for independent iterations.

    • R Alternatives: data.table for fast data manipulation; apply family (lapply, sapply) or purrr::map().

3.4.2 Debugging Techniques

  • Interactive Debuggers:

    • MATLAB: Set breakpoints in Editor; use dbstop if error to stop on error. Commands: dbstep, dbcont, dbquit.

    • R (RStudio): Click gutter to set breakpoints; use debugonce(func) or insert browser() in code.

  • Strategic Printing:

    • MATLAB: disp(var), fprintf('Value: %.2f\n', val).

    • R: print(var), cat("Value:", val, "\n").

  • Common Pitfall: Forgetting to clear breakpoints (dbclear all in MATLAB) or undebug(func) in R.

3.4.3 Writing Robust & Reproducible Code

  • Input Validation: Check function arguments (nargin, nargout in MATLAB; missing() or stopifnot() in R).

  • Error Handling:

    • MATLAB: try ... catch ME; fprintf('Error: %s\n', ME.message); end.

    • R: tryCatch(expr, error = function(e) { message("Error: ", e$message) }).

  • Documentation:

    • MATLAB: Help comments % at top of function; help func displays them.

    • R: roxygen2 comments (#') to generate .Rd help files; devtools::document().

  • Scripts vs. Functions: Use functions for reusable, encapsulated code (avoids workspace side-effects). Scripts for linear workflows.

  • Reproducibility: Set random seed (rng(123) in MATLAB; set.seed(123) in R). Use relative paths; manage dependencies.

[!TIP] Golden Rule: Preallocate arrays in loops. This is the #1 performance fix in both languages. Use the profiler to find bottlenecks—often it's not where you think.


3.5 Interoperability & Advanced Integration

3.5.1 Calling R from MATLAB

  • Requires R installation and MATLAB's R interface (check ismember('r',feature('lang'))).

  • Basic Workflow:

    
    % Start R engine (R2020b+)
    
    rng = matlab.engine.start_matlab(); % Actually starts MATLAB engine from R; reverse here.
    
    % Correct for MATLAB->R: Use legacy 'r' interface or system calls.
    
    % Legacy (older):
    
    r = Rinterface; % Not standard; often use system().
    
    % Modern/Practical: Use system() to call Rscript.
    
    system('Rscript myRscript.R');
    
    
  • Data Transfer: Write data from MATLAB to .csv or .mat, read in R. Or use R = matlab.engine.connect_matlab() (from R side) – typically easier to call MATLAB from R than vice-versa.

3.5.2 Calling MATLAB from R

  • Package: R.matlab (CRAN).

  • Workflow:

    
    library(R.matlab)
    
    # Write data from R to .mat file
    
    writeMat("data.mat", var1 = r_vector, var2 = r_df)
    
    # Start MATLAB session and read
    
    matlab <- Matlab()
    
    matlab$put("r_var", r_vector)
    
    matlab$eval("result = myMatlabFunc(r_var);")
    
    matlab$get("result")
    
    matlab$close()
    
    
  • Alternative: Use system('matlab -batch "myFunc"') to run MATLAB non-interactively.

3.5.3 Using System Commands & External Scripts

  • MATLAB:

    • status = system('ls -l') (Linux/macOS) or dos('dir') (Windows).

    • unix('Rscript analysis.R') to run R script.

    • Returns exit status; output captured as string.

  • R:

    • system("ls -l", intern=TRUE) captures output.

    • system2("matlab", args = c("-batch", "myFunc"), stdout=TRUE).

  • Use Case: Integrate proprietary MATLAB code into R pipeline or vice-versa; leverage OS-specific tools.

[!TIP] Critical Note: Direct in-memory engine calls (MATLAB engine API for R, R.matlab) can be fragile across versions. File-based exchange (.csv, .mat) is often more robust for production pipelines.


3.6 Application Development & Deployment (Conceptual Overview)

3.6.1 Building Simple User Interfaces

  • MATLAB:

    • App Designer: Drag-and-drop UI builder (.mlapp files). Generates code with components as properties. Recommended for new apps.

    • Programmatic UI: Use uifigure and uicontrol/uibutton etc. for full code control.

    • Callback Structure: app.Button.ValueChangedFcn = @(src,event) myCallback(app, src, event);.

  • R:

    • Shiny: Reactive web apps.

      • UI: fluidPage(titlePanel(), sidebarLayout(sidebarPanel(), mainPanel())).

      • Server: function(input, output) { output$plot <- renderPlot({ ... }) }.

      • Reactivity: input$slider, reactive({ ... }), observeEvent().

    • Deployment: Can run locally or deploy to shinyapps.io, Shiny Server.

3.6.2 Packaging & Sharing Code

  • MATLAB:

    • Toolbox: Package functions, classes, apps into .mltbx installer. Use matlab.addons.toolbox.packageToolbox.

    • Sharing: Distribute toolbox file; users install via Add-On Explorer.

    • Best Practice: Use +package folders for namespaces.

  • R:

    • Package Structure: DESCRIPTION, NAMESPACE, R/ (functions), man/ (documentation).

    • Development: devtools::create("mypkg"); devtools::load_all() for testing.

    • Documentation: roxygen2 comments → devtools::document() → .Rd files.

    • Sharing: Submit to CRAN (strict) or GitHub (use devtools::install_github("user/pkg")).

3.6.3 Generating Reports & Dynamic Documents

  • MATLAB:

    • Live Scripts (.mlx): Combine code, output, formatted text, equations ($...$). Publish to HTML, PDF, LaTeX via Publish tab or publish('script.m', 'pdf').

    • Advantage: WYSIWYG, integrated graphics.

  • R:

    • R Markdown (.Rmd): Markdown with embedded R code chunks ({r}). Knit to HTML, PDF, Word.

    • Workflow: Write narrative, run code chunks, output (tables, plots) embedded. Reproducible research standard.

    • Parameterized Reports: Use params field for dynamic inputs (e.g., rmarkdown::render("report.Rmd", params = list(date = Sys.Date()))).

[!TIP] For Exams: Know that Shiny is R's primary app framework; App Designer is MATLAB's. R Markdown is to R as Live Scripts are to MATLAB. Both enable reproducible, dynamic reports.

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