Page 2: Variables, Data Types, and Array Manipulation

2. Variables, Data Types, and Array Manipulation

At its core, MATLAB excels at numerical computation, primarily through its robust handling of arrays (vectors and matrices). Everything in MATLAB is fundamentally an array.

2.1. Declaring Variables and Basic Data Types

Variables are created simply by assigning a value. MATLAB automatically infers the data type.

2.2. Creating and Manipulating Arrays (Vectors & Matrices)

Arrays are fundamental. Use square brackets [] to create them, spaces or commas to separate columns, and semicolons ; to separate rows.

>> row_vector = [1 2 3 4];
>> col_vector = [5; 6; 7; 8];
>> matrix = [10 20 30; 40 50 60];

>> % Indexing (MATLAB is 1-based)
>> matrix(1, 2) % Access element at row 1, column 2
ans =
    20

>> % Slicing (colon operator)
>> matrix(1, :) % First row
ans =
    10    20    30
>> matrix(:, 2) % Second column
ans =
    20
    50

>> % Element-wise operations (use dot operator for arrays)
>> A = [1 2; 3 4]; B = [5 6; 7 8];
>> C_elem_mult = A .* B; % Element-wise multiplication
>> C_matrix_mult = A * B; % Matrix multiplication (linear algebra)

Key Concept: MATLAB's strength lies in its ability to perform high-performance operations on entire arrays with concise syntax, avoiding explicit loops in many cases.