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

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

UNIT 2: PROGRAMMING FUNDAMENTALS & DATA MANIPULATION


2.1 Core Programming Constructs & Control Flow

Conditional Statements

  • MATLAB: if, elseif, else, switch (with case).

  • R: if, else if, else; switch() for multiple values; ifelse() for vectorized conditionals.

  • [!TIP] ifelse() in R is vectorized—operates on entire vectors without loops. MATLAB’s if is scalar; use logical indexing for vectorized conditionals.

Loops

  • for loops: iterate over indices (for i=1:n) or values (for val in array).

  • while loops: repeat while condition true.

  • Loop control: break (exit loop), continue (skip to next iteration).

  • [!CAUTION] Nested loops increase time complexity to $$\displaystyle O(n^2) $$; avoid for large datasets.

Logical & Relational Operators

Operator MATLAB R
AND (scalar) && &&
AND (element-wise) & &
OR (scalar) `
OR (element-wise) | |
NOT ~ !
Equal == ==
Not equal ~= !=

Vectorization

  • Definition: Performing operations on entire arrays/matrices directly, avoiding explicit loops.

  • Benefit: Leverages optimized BLAS/LAPACK libraries; significantly faster (often $O(n)$ vs. $O(n)$ with lower constant factor for loops).

  • Example (MATLAB): C = A + B; vs. for i=1:length(A), C(i)=A(i)+B(i); end.

  • Example (R): x * 2 vs. for(i in 1:length(x)) x[i] <- x[i]*2.

  • [!TIP] Exam Focus: Always prefer vectorized operations in MATLAB; in R, use apply() family or vectorized functions like ifelse().


2.2 Functions & Modular Programming

Defining Functions

  • MATLAB:

    • Function file: function [out1, out2] = name(in1, in2) ... end.

    • Anonymous function: f = @(x) x.^2;.

  • R:

    • name <- function(arg1, arg2) { ... return(out) }.

    • No separate file required; can be defined in scripts.

Function Components

  • Input arguments: Passed by value (copy-on-write in MATLAB; R uses pass-by-promise).

  • Output/return: MATLAB: assign to function name or use return(); R: last expression or return().

  • Scope: Variables inside function are local by default. Use global (MATLAB) or <<- (R) for global (avoid if possible).

  • [!CAUTION] Modifying global variables leads to hard-to-debug code; prefer returning values.

Calling Functions

  • Positional arguments: Order matters.

  • Named arguments (R only): fun(arg1=val1, arg2=val2)—improves readability.

Built-in Functions

  • Mathematical: sin, cos, exp, log (both).

  • Statistical: mean, median, std, var (both); summary() (R) gives quick stats.

  • Utility: size/length (MATLAB); length, dim (R).

Scripts vs. Functions

Feature Script Function
Workspace Base workspace Separate local workspace
Input/Output Uses variables in base workspace Explicit inputs/outputs
Reusability Low High
Side effects Can modify base variables No (unless global)
  • [!TIP] Use functions for reusable, testable code; use scripts for linear workflows or quick exploration.


2.3 Data Structures & Manipulation

MATLAB

Structure Creation Indexing Key Notes
Array/Matrix A = [1,2;3,4]; zeros(m,n) Subscript: A(i,j); Linear: A(k) Homogeneous (numeric/logical).
Cell Array C = {1, 'text'; [1,2]} Content: C{i,j}; Cell: C(i,j) Heterogeneous; use {} for contents.
Structure s.name = 'John'; s.age = 30; s.field or s.(fieldname) Named fields; good for records.
Table T = readtable('file.csv') T.VarName or T{row,col} Tabular data; variable/row names.

R

Structure Creation Indexing Key Notes
Vector v <- c(1,2,3) v[i] (single) or v[c(1,3)] Homogeneous; type coercion (e.g., c(1,'a') → character).
Matrix m <- matrix(1:4, nrow=2) m[i,j] Homogeneous; dim(m), nrow(m), ncol(m).
List lst <- list(a=1, b='text') lst[[i]] (element); lst[i] (sublist) Heterogeneous; [[ ]] extracts element.
Data Frame df <- data.frame(x=1:3, y=c('a','b','c')) df$col, df[i,j], subset(df, cond) Tabular; str(df), summary(df).
Factor f <- factor(c('low','med','high')) f[i] Categorical; levels(f), ordered=TRUE for ordinal.
  • [!TIP] In R, [[ ]] extracts the element (drops wrapper), [ ] returns a sub-list/data frame. In MATLAB, () indexes cells, {} accesses contents.


2.4 Data Input/Output & Basic Preprocessing

Importing Data

  • MATLAB: T = readtable('file.csv') (tabular); M = readmatrix('file.csv') (numeric matrix); importdata (flexible).

  • R: df <- read.csv('file.csv'); df <- read.table('file.txt', sep='\t'); library(readr); df <- read_csv('file.csv') (faster, no factors by default).

Exporting Data

  • MATLAB: writetable(T, 'out.csv'); writematrix(M, 'out.txt').

  • R: write.csv(df, 'out.csv', row.names=FALSE).

Basic Inspection

  • MATLAB: size(A), length(v), whos (list variables), class(x).

  • R: dim(df), nrow(df), ncol(df), str(df) (structure), summary(df), head(df), tail(df).

Handling Missing Data

  • Identify: isnan(A) (MATLAB); is.na(df) (R).

  • Remove: rmmissing(A) (MATLAB); df[complete.cases(df), ] or na.omit(df) (R).

  • Impute: Simple strategies: replace with mean/median (fillmissing in MATLAB; df$col[is.na(df$col)] <- mean(df$col, na.rm=TRUE) in R).

  • [!CAUTION] na.omit() removes entire rows with any NA; may lose data. Consider imputation for critical features.


2.5 Applied Data Analysis & Visualization Basics

Descriptive Statistics

Statistic MATLAB R
Mean mean(x) mean(x, na.rm=TRUE)
Median median(x) median(x, na.rm=TRUE)
Standard Deviation std(x) sd(x, na.rm=TRUE)
Variance var(x) var(x, na.rm=TRUE)
Min/Max min(x), max(x) min(x, na.rm=TRUE), max(x, na.rm=TRUE)
Summary summary(x) (for table) summary(df) (detailed)

Basic Plotting

  • MATLAB:

    • Line plot: plot(x,y).

    • Scatter: scatter(x,y).

    • Histogram: histogram(data).

    • Labels: xlabel('X'), ylabel('Y'), title('Title'), legend('label').

  • R:

    • Base R: plot(x,y), hist(data), boxplot(data).

    • ggplot2: Grammar of graphics.

      
      library(ggplot2)
      
      ggplot(df, aes(x=var1, y=var2)) + geom_point() + labs(title="Title")
      
      
  • [!TIP] In R, ggplot2 is layered and highly customizable; base R is quicker for simple plots.

Simple Data Transformations

  • MATLAB: Arithmetic on arrays (A.*B element-wise); arrayfun(@func, A), cellfun(@func, C).

  • R: Vectorized operations (x + 1); apply(df, 2, mean) (columns); lapply(lst, func) (list); sapply(lst, func) (simplified).


2.6 Debugging & Code Efficiency (Introductory)

Common Errors

  • Syntax: Missing end, mismatched braces/parentheses.

  • Dimension mismatch: A + B where sizes differ (MATLAB); cbind with unequal lengths (R).

  • Type coercion: Implicit conversion (e.g., numeric to character in R vectors).

  • Undefined variable: Typos or using variable before assignment.

  • [!CAUTION] In R, $$\displaystyle ` indexing fails if column name has spaces/special chars; use backticks: `df $$column name`` or df[["column name"]].

Debugging Tools

  • MATLAB:

    • Editor/Debugger: set breakpoints, step through.

    • dbstop if error: stops at error.

    • disp(), fprintf() for output.

  • R:

    • traceback(): shows call stack after error.

    • debug(func): step into function.

    • browser(): pause execution.

    • print(), cat() for output.

Profiling & Efficiency

  • MATLAB: profile on → run code → profile viewer; identifies slow functions.

  • R: Rprof("prof.out") → code → Rprof(NULL); summaryRprof("prof.out").

  • Pre-allocation (Critical for MATLAB):

    
    % Inefficient:
    
    A = [];
    
    for i=1:n
    
        A(i) = i^2;  % Grows array each iteration → slow
    
    end
    
    % Efficient:
    
    A = zeros(1,n);  % Pre-allocate
    
    for i=1:n
    
        A(i) = i^2;
    
    end
    
    
    • Time complexity remains $O(n)$ but constant factor is much lower.

    • In R, pre-allocate with vector() or numeric(n); lapply often avoids explicit loops.

  • [!TIP] Exam Question: "Explain why pre-allocation improves performance in MATLAB." Answer: Avoids repeated memory allocation/copying during loop iterations.

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