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

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

ME-705: MATLAB and R Programming - UNIT 1 Short Notes

Theme: Foundations, Syntax, and Basic Data Manipulation


1.0 Introduction & Environment Setup

1.1 Purpose and Application Domains

Feature MATLAB R
Primary Domain Engineering, Numerical Computation, Simulation, Control Systems Statistics, Data Analysis, Visualization, Academic Research
Core Strength Matrix/Vector operations, built-in toolboxes (Simulink, Image Processing) Statistical modeling, extensive packages (CRAN), ggplot2 for graphics
Typical Users Engineers, Scientists Statisticians, Data Scientists, Researchers

1.2 Installing and Launching

  • MATLAB:

    • Requires license (institutional/personal).

    • Desktop Environment:

      • Command Window: Interactive command execution.

      • Workspace: Shows current variables.

      • Current Folder: File browser.

      • Editor: Write and run scripts (.m files).

  • R:

    • Free, open-source. RStudio is the highly recommended IDE.

    • RStudio Panes:

      • Console: Interactive R commands.

      • Source: Script editor (.R files).

      • Environment/History: Variables and command history.

      • Files/Plots/Help: File navigation, plot viewer, documentation.

1.3 Getting Help and Documentation

Task MATLAB R
General Help help function_name help(function_name) or ?function_name
Search Keywords lookfor keyword help.search("keyword")
Detailed Docs doc function_name (opens browser) ?function_name (often same as help)
Run Examples Examples in doc pages example(function_name)

[!TIP] Common Pitfall: In R, help.start() opens the main HTML help page. In MATLAB, doc without arguments opens the main documentation browser.


2.0 Basic Syntax, Arithmetic, and Variables

2.1 Command Line vs. Script/File Execution

  • Interactive (Command Line/Console): Execute commands one-by-one. Good for testing.

  • Script Execution: Write a sequence of commands in a file (.m for MATLAB, .R for R) and run the entire file. Essential for reproducibility.

2.2 Arithmetic and Logical Operators

  • Arithmetic: +, -, *, / (element-wise), ^ (power), \ (left division in MATLAB).

  • Relational: == (equal), ~= (MATLAB) / != (R) (not equal), >, <, >=, <=.

  • Logical:

    • Element-wise: & (AND), | (OR), ~ (NOT) - operate on arrays element-by-element.

    • Short-circuit: && (AND), || (OR) - evaluate left to right, stop if outcome determined. Used in if conditions.

    • R Note: ! is used for NOT (e.g., !x).

2.3 Variables and Assignment

  • Naming Rules: Must start with a letter, can contain letters, digits, underscores. Case-sensitive in both.

  • Assignment Operators:

    • MATLAB: Only =. Example: x = 5;

    • R: = (common) or <- (traditional). Example: x <- 5 or x = 5.

  • Inspecting/Clearing Variables:

    | Task | MATLAB | R | | :--- | :--- | :--- | | List variables | who (names only), whos (details) | ls() or objects() | | Clear variable(s) | clear x or clear all | rm(x) or rm(list=ls()) |

[!TIP] Critical Difference: MATLAB uses ~= for "not equal", R uses !=. MATLAB's && and || are scalar-only (for if), while & and | are array operators. In R, & and | are vectorized, && and || are scalar.


3.0 Core Data Structures & Objects

3.1 Vectors (1D Arrays)

Feature MATLAB R
Creation v = [1, 2, 3] (commas/space), v = 1:5 (colon), linspace(1,10,5) v = c(1, 2, 3), v = 1:5
Indexing 1-based. v(1) (first element). Colon for ranges: v(2:4) 1-based. v[1] (single [ ] returns vector), v[[1]] (extracts single element).
Vectorized Ops Yes. v * 2, v.^2 (element-wise square). Yes. v * 2, v^2 (element-wise by default).

3.2 Matrices & 2D Arrays

Feature MATLAB R
Creation M = [1,2; 3,4] (semicolon for new row). zeros(3), ones(2,4), eye(3), rand(3) M = matrix(1:4, nrow=2, byrow=TRUE) or M = rbind(c(1,2), c(3,4))
Indexing M(row, col). M(1,:) (first row), M(:,2) (second column). M[row, col]. M[1,], M[,2]. Single bracket [ ] returns matrix, double [[ ]] extracts element.
Key Ops * (matrix multiplication), .^ (element-wise power), ' (transpose/conjugate), .' (transpose) %*% (matrix multiplication), ^ (element-wise), t(M) (transpose)

3.3 Lists and Cell Arrays (Heterogeneous)

Feature MATLAB: Cell Arrays R: Lists
Creation C = {1, 'text', [1 2 3]} (curly braces {}) L = list(1, "text", c(1,2,3))
Accessing C{1} (contents of first cell), C{2}. C(1) returns a cell. L[[1]] (first element), L$name (if named). L[1] returns sub-list.
Use Case Store different data types in one array. Store different objects (vectors, matrices, other lists) in one object.

3.4 Other Fundamental Types

  • Scalars: Single values (numeric, integer, character/string, logical true/false or 1/0).

  • R-Specific:

    • Factors: Categorical data. f = factor(c("low", "med", "high")). Stores levels efficiently.

    • Data Frames: Tabular data. Like a list of equal-length vectors (columns). df = data.frame(col1=1:3, col2=c("a","b","c")). Primary structure for statistical datasets. Subset with df$col1, df[,1], or df[["col1"]].

[!TIP] Key Distinction: MATLAB's fundamental array is the numeric matrix (all elements same type). R's fundamental structure is the vector (all elements same type). Data frames in R are lists of vectors.


4.0 Control Flow & Programmatic Logic

4.1 Conditional Statements


% MATLAB

if x > 0

    disp('Positive');

elseif x == 0

    disp('Zero');

else

    disp('Negative');

end


# R

if (x > 0) {

  print("Positive")

} else if (x == 0) {

  print("Zero")

} else {

  print("Negative")

}

[!CAUTION] Syntax Difference: MATLAB uses elseif (one word), R uses else if (two words). R requires parentheses around condition in if.

4.2 Loops

  • for Loop (Iterating over values/indices):

    
    % MATLAB: Iterate over columns of matrix A
    
    for i = 1:size(A,2)
    
        col_sum = sum(A(:,i));
    
    end
    
    
    
    # R: Iterate over vector elements
    
    for (val in 1:5) {
    
        print(val^2)
    
    }
    
    
  • while Loop (Condition-based):

    
    % MATLAB
    
    while abs(x - guess) > tolerance
    
        guess = guess / 2;
    
    end
    
    
    
    # R
    
    while (abs(x - guess) > tolerance) {
    
        guess <- guess / 2
    
    }
    
    

[!TIP] Golden Rule: Vectorize whenever possible. Both MATLAB and R are optimized for operations on entire vectors/matrices. Loops are often slower. Example: y = sin(x) is faster than for i=1:length(x), y(i)=sin(x(i)); end.


5.0 Basic Data Import/Export & Inspection

5.1 Reading Data from Files

Task MATLAB R
CSV/Text T = readtable('data.csv') (returns table), M = readmatrix('data.csv') df = read.csv('data.csv') (base R), df = read_csv('data.csv') (faster, readr package)
General Text data = importdata('data.txt') df = read.table('data.txt', header=TRUE)

5.2 Writing Data to Files

Task MATLAB R
Write Table writetable(T, 'out.csv') write.csv(df, 'out.csv', row.names=FALSE)
Write Matrix writematrix(M, 'out.txt') write.table(M, 'out.txt')

5.3 Inspecting Data Objects

Command MATLAB R Purpose
Structure whos (detailed list) str(df) Most important. Shows structure, types, preview.
Dimensions size(M) (rows, cols), length(v) dim(df), nrow(df), ncol(df)
Class/Type class(x) class(df)
Summary Stats Limited (mean, std on data) summary(df) R: Provides min, max, quartiles, mean for numeric; counts for factors.

6.0 Basic Visualization (Introduction)

6.1 Quick Plotting for Exploration

  • MATLAB:

    
    x = 0:0.1:2*pi;
    
    y = sin(x);
    
    plot(x, y, 'b-'); % Blue solid line
    
    xlabel('x'); ylabel('sin(x)'); title('Sine Wave');
    
    scatter(x, y); % Scatter plot
    
    
  • R (Base Graphics):

    
    x <- seq(0, 2*pi, by=0.1)
    
    y <- sin(x)
    
    plot(x, y, type='l', col='blue') # 'l' for line
    
    title("Sine Wave"); xlab("x"); ylab("sin(x)")
    
    hist(y) # Histogram
    
    boxplot(df$variable) # Boxplot
    
    

[!TIP] Philosophy: MATLAB's plot is function-based. R's base graphics are state-based (plot sets up a "device"). For publication-quality, R's ggplot2 (grammar of graphics) is dominant but has a steeper learning curve.

6.2 Saving Figures

Task MATLAB R
Save Current Figure saveas(gcf, 'figure.png') dev.copy(png, 'figure.png'); dev.off() (base)
High-Quality Print print('-dpdf', 'figure.pdf') ggsave('figure.pdf') (for ggplot2 objects)

Summary Comparison Table: Key Distinctions

Concept MATLAB R
Primary Data Unit Matrix (numeric, double) Vector (atomic, same type)
Indexing A(i,j) (parentheses) A[i,j] (brackets)
Assignment = = or <-
Matrix Multiply * %*%
Element-wise Ops .*, .^, ./ *, ^, / (vectorized by default)
Transpose ' (conjugate) or .' t(A)
Comment % #
Block Delimiters end {} (curly braces)
Help doc ? or help
Logic in if &&, || (scalar) &&, || (scalar), &, | (vectorized)
DiagramCANVAS: A side-by-side illustration showing a MATLAB workspace (Command Window, Workspace panel) and RStudio interface (Console, Environment, Source pane) with arrows pointing to key elements.
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