Skip to content
Feb 25

MATLAB Fundamentals: Variables and Arrays

MT
Mindli Team

AI-Generated Content

MATLAB Fundamentals: Variables and Arrays

MATLAB, short for Matrix Laboratory, is built on a simple yet powerful foundation: everything is an array. Mastering how to create, manipulate, and index these arrays is the single most important skill for any engineer using MATLAB. Whether you're analyzing sensor data, solving systems of equations, or simulating dynamic systems, your efficiency depends on understanding these fundamentals.

The Workspace and Variable Creation

When you launch MATLAB, you interact primarily with the Command Window and the Workspace. The Workspace is MATLAB's memory manager; it's a live list of all the variables you have created during your session, along with their values, size, and type. You create a variable simply by assigning a value to a name using the equals sign =. MATLAB is dynamically typed, meaning you don't have to declare a variable's type beforehand.

>> sensorReading = 3.1416
>> projectName = 'WindTunnel_Test_01'

In the first line, MATLAB creates a variable named sensorReading and assigns it the numeric value 3.1416. In the second, it creates a variable projectName and assigns it a character array. Variable names must begin with a letter and can contain letters, digits, and underscores. It's good practice to use descriptive names.

Scalars, Vectors, and Matrices

In MATLAB, even a single number is technically a 1x1 array, called a scalar. The real power comes from ordered collections of numbers.

A vector is a one-dimensional array. You create a row vector by enclosing elements in square brackets, separated by spaces or commas.

>> position = [10, 20, 30] % A 1x3 row vector

You create a column vector by separating elements with semicolons.

>> velocity = [1.2; 0.5; -0.1] % A 3x1 column vector

A matrix is a two-dimensional rectangular array. You define it by rows, using spaces or commas between elements in a row, and semicolons to separate rows.

>> stiffnessMatrix = [200, -100, 0; -100, 200, -100; 0, -100, 200]

This creates a 3x3 matrix. The fundamental rule is that all rows must have the same number of elements. The size() function tells you the dimensions of any array.

Indexing and the Colon Operator

To access or change a specific element in an array, you use indexing. MATLAB uses 1-based indexing, meaning the first element of an array is at position 1. You specify the indices in parentheses.

>> A = [5, 10, 15; 20, 25, 30];
>> element = A(2, 3) % Gets the element in row 2, column 3 (value: 30)
>> A(1,2) = 99 % Changes the element in row 1, column 2 to 99

The colon operator : is one of MATLAB's most versatile tools. By itself, it creates a sequentially spaced vector.

>> time = 0:0.1:1 % Creates a vector from 0 to 1 in steps of 0.1: [0, 0.1, 0.2, ..., 1]

In indexing, a colon selects all elements along that dimension.

>> rowTwo = A(2, :) % Gets all columns of the second row
>> firstColumn = A(:, 1) % Gets all rows of the first column
>> subMatrix = A(1:2, 2:3) % Gets rows 1-2 and columns 2-3

You can also use the end keyword to reference the last element in a dimension: A(1, end) gets the last element of the first row.

Element-wise vs. Matrix Operations

This is a critical distinction. By default, MATLAB is designed for matrix operations, which follow the rules of linear algebra.

Matrix multiplication uses the * operator. For A * B to be valid, the inner dimensions must agree: if A is m x n, B must be n x p.

>> C = [1, 2; 3, 4];
>> D = [5; 6];
>> result = C * D % Valid: (2x2) * (2x1) yields a (2x1) vector. Linear algebra operation.

Often in engineering, you want to perform an operation on each corresponding element of two identically-sized arrays (e.g., multiplying two sets of sensor readings point-by-point). This is an element-wise operation. You precede the standard operator with a dot ..

>> V = [1, 2, 3];
>> I = [4, 5, 6];
>> power = V .* I % Element-wise multiplication: [1*4, 2*5, 3*6] = [4, 10, 18]

Other element-wise operators include ./ (element-wise division) and .^ (element-wise exponentiation). For addition and subtraction, the matrix and element-wise operations are identical, so + and - are used.

Character Arrays, Strings, and Logical Arrays

Character arrays store text as a sequence of characters. Each character occupies its own element in an array.

>> word = 'MATLAB'; % A 1x6 character array
>> char(word(3)) % Accesses the third character: 'T'

For simpler text handling, MATLAB also supports string arrays defined with double quotes, which treat a piece of text as a single entity.

Logical arrays are arrays whose elements are the values true (1) or false (0). They are created as the result of comparison operations (>, <, ==, ~=, etc.) and are incredibly useful for filtering data.

>> data = [5, 15, 8, 20, 3];
>> highValues = data > 10 % Returns a logical array: [0, 1, 0, 1, 0]
>> extractedData = data(highValues) % Uses logical indexing to get [15, 20]

Common Pitfalls

  1. Confusing Matrix and Element-wise Multiplication: The most common error for beginners. Using * on two vectors of the same length will fail unless one is a row and the other a column (for a dot product). For point-by-point operations, you almost always want .*. Always check your array dimensions with size().
  2. Off-by-One Indexing Errors: Remember, MATLAB indices start at 1, not 0. Trying to access A(0) will cause an error. Similarly, if a vector has 10 elements, the valid indices are 1 through 10. Using A(11) will cause an index exceeds array bounds error.
  3. Ignoring Array Dimensions: Attempting to combine or perform operations on arrays of incompatible sizes is a primary source of errors. A 1x5 row vector and a 5x1 column vector are not the same shape for element-wise operations. Use the transpose operator ' to convert between them if needed: rowVector' creates a column vector.
  4. Using the Wrong Type of Quote: Single quotes (') create character arrays. Double quotes (") create string types. Mixing them up, especially when concatenating, can lead to unexpected results or errors. For beginners, stick with single quotes for simple text unless you specifically need string features.

Summary

  • The workspace is MATLAB's active memory. You create a variable by assigning a value to a name with =.
  • Everything in MATLAB is an array: a single number is a scalar, a list is a vector, and a 2D table is a matrix.
  • Indexing (using parentheses A(i,j)) and the colon operator : (for creating sequences and selecting ranges) are essential for accessing and manipulating array data.
  • Matrix operations (*, /, ^) follow linear algebra rules. Element-wise operations (.*, ./, .^) act on corresponding elements and are used for most numerical calculations.
  • Character arrays store text, and logical arrays (containing true/false) are created by comparisons and used for powerful data filtering via logical indexing.

Write better notes with AI

Mindli helps you capture, organize, and master any subject with AI-powered summaries and flashcards.