MATLAB Elements and Syntax

1. Basic Elements

Comment: A comment in MATLAB is a piece of text in a script or function that is not executed. Comments are used to explain code and are created using the percent sign. For example, x = 10 % This is a comment assigns 10 to x and includes a comment. You can also write a block of comments using the block comment operators % { and % }.

Variable: A variable in MATLAB is a storage location identified by a name that can hold different types of data such as numbers, arrays, or strings. Variables are created by assignment statements, for example, x = 5 creates a variable x with a value of 5.

String: A string is a series of characters, sometimes called a character vector or character array. Strings are created using single quotes, e.g., str = 'hello' creates a string variable str with the text hello.

Array: An array is a data structure in that can store values of the same type. Arrays are created using square brackets and can be one-dimensional (e.g., vectors) or multi-dimensional (e.g., matrices).

  • Vector: A vector is a one-dimensional array that can hold a sequence of variables Vectors can be either row vectors or column vectors.
    • A row vector is created by enclosing the elements in square brackets, separated by spaces or commas, e.g., 'rowVec = [1, 2, 3]' creates a 1x3 row vector.
    • A column vector is created by enclosing the elements in square brackets, separated by semicolons, e.g., 'colVec = [1; 2; 3]' creates a 3x1 column vector.
  • Matrix: A matrix is a two-dimensional array of numbers arranged in rows and columns. Matrices are created using square brackets with rows separated by semicolons, e.g., A = [1, 2, 3; 4, 5, 6] creates a 2x3 matrix.
  • String Array:: A string array is a one-dimensional or multidimensional array that holds strings. For example, strArray = ["Hello", "World"] creates a 1x2 string array.

Cell: A cell (sometimes referred to as a cell array) is a data structure in MATLAB that can hold different types of data in an array format. Each element of a cell array is called a cell, and it can contain different types or sizes of data. Cell arrays are created using curly braces, e.g., C = {1, 'text', [1, 2, 3]} creates a cell array with three elements: a number, a string, and a vector.

Function: A function is a block of code designed to perform a specific task. Functions in MATLAB are defined using the function keyword and can accept inputs and return outputs. For example, function y = add(x1, x2) defines a function named add that takes two inputs and returns their sum. Functions help in organizing and reusing code.

Structure: A structure is a data type in MATLAB that organizes data into fields, each containing a different type of data. Structures are useful for grouping related data. They are created using the struct function or by directly assigning values to fields, e.g., S.name = 'John'; S.age = 25; creates a structure S with fields name and age.

Table: A table is a data type in MATLAB for storing column-oriented or tabular data, such as in a spreadsheet or database. Tables are created using the table function, and they can store variables of different types and sizes, e.g., T = table(Age, Height, Weight) where Age, Height, and Weight are variables representing columns.

To help you identify elements, some entries appear in different colors in the Command Window and Editor. By default:

  • Keywords are blue.
  • Character vectors and strings are purple.
  • Unterminated character vectors are maroon.
  • Comments are green.

image

2. Special Characters

Below are some of the key special characters you should be familiar with, including delimiters which are what the lists of variables are enclosed by when creating arrays and cells. For detailed information about other special characters, see MATLAB Operators and Special Characters.

Square Brackets []:

  • A delimiter used to create arrays and matrices
    • Example: A = [1, 2, 3]).

Curly Braces {}:

  • A delimiter used to create cells
    • Example: C = {1, 'text', [1, 2, 3]}).
  • Indexing cells
    • Example: cellArray{index} = newValue.

Parentheses ():

  • Group expressions
    • Examples: a = (b + c) * d).
  • Function arguments
    • Example: result = myFunction(arg1, arg2).
  • Indexing arrays
    • Example: element = A(row, column).

Comma ,

  • Separates elements in arrays and function arguments.
    • Example: [1, 2, 3] or plot(x, y).

Colon :

  • Creates vectors and specify ranges, and index arrays.
    • Example: 1:5 generates a vector [1, 2, 3, 4, 5].
  • The colon alone, without start or end values, specifies all of the elements in that dimension.
    • Example: A(:, 2) selects all rows from the second column of matrix A.

Semicolon ;

  • Suppresses the output of a command.
    • Example: a = 5; assigns 5 to a without displaying the output.
  • Separates rows in matrix definitions.
    • Example: A = [1, 2; 3, 4].

Ellipsis ...

  • Indicates that a statement continues on the next line.
    • Example:
      a = 1 + 2 + 3 + ...
          4 + 5 + 6;
      
      Double Percent Signs %%
  • Starts a code section and is typically followed by the section title
    • Example: %% first code section starts a section titled first code section without displaying the output.

3. Accessing and Manipulating Elements

Indicies: Indices are used to specify the position of the element(s) so that you can retrieve them without processing the entire dataset. This capability enables you to easily update or modify specific elements within data structures or extract relevant portions of data for analysis or visualization.

For one-dimensional arrays or cells, you specify the element's position using a single index, which corresponds to the element's position in that dimension. For example:

rowVector = [10, 20, 30, 40, 50];
thirdElement = rowVector(3);  % The 3 is an index for third element in the row, which is 30

colVector = [10; 20; 30; 40; 50];
fourthElement =colVector(4);  %  The 4 is an index for fourth element in the column, which is 40

For multi-dimensional arrays or cells, you specify the element's position using a pair of indices (or more for higher dimensions), which correspond to the element's row and column positions. For example:

matrix = [1, 2, 3; 4, 5, 6; 7, 8, 9];
element = matrix(2, 3);  % These indicies are specifying the element in the second row and third column, which is 6

Accessing Elements: Access element(s) with the appropriate indicies and delimiter (e.g., parantheses or cell braces).To access a subset of elements, you must specify the range using the colon : operator. For example:


% Vectors
v = [10, 20, 30, 40, 50];
v(2);          % Accesses the second element, result is 20
v(2:4);               % Accesses elements from the second to the fourth, result is [20, 30, 40]

% Matrices
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
A(2,1);              % Accesses the element in the second row, first column, result is 4
A(1:2, 2:3);          % Accesses a submatrix from rows 1 to 2 and columns 2 to 3, result is [2, 3; 5, 6]

% One-dimensional String Arrays
strArray = ["Hello", "World", "MATLAB"];
strArray(1);    % Accesses the first element, result is "Hello"
strArray(1:2);        % Accesses the first two elements, result is ["Hello", "World"]

% Multi-dimensional String Arrays
multiStrArray = ["Hello", "World"; "MATLAB", "Programming"];
multiStrArray(1, 2); % Accesses the element in the first row, second column, result is "World"
multiStrArray(1:2, 1); % Accesses the first column, result is ["Hello"; "MATLAB"]

% One-dimensional Cell Arrays
cellArray = {1, 'MATLAB', [2, 3, 4]};
cellArray{1};   % Accesses the first element, result is 1
cellArray{2:3};       % Accesses elements from the second to the third, result is {'MATLAB', [2, 3, 4]}

% Multi-dimensional Cell Arrays
multiCellArray = {1, 'text'; 2, 'more text'; 3, 'even more text'};
cellArray{2, 1};   % Accesses the element in the second row, first column, result is 2
multiCellArray{2:3, 2}; % Accesses elements from rows 2 to 3 in column 2, result is {'more text', 'even more text'}

Modifying Elements: Change element(s) by using the = to assign a new value to the corresponding index.

% Vectors
v = [10, 20, 30, 40, 50];
v(2) = 25;                % Modifies the second element, result is [10, 25, 30, 40, 50]
v(2:4) = [21, 31, 41];    % Modifies elements from the second to the fourth, result is [10, 21, 31, 41, 50]

% Matrices
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
A(2,1) = 40;              % Modifies the element in the second row, first column, result is [1, 2, 3; 40, 5, 6; 7, 8, 9]
A(1:2, 2:3) = [20, 30; 50, 60];  % Modifies a submatrix from rows 1 to 2 and columns 2 to 3, result is [1, 20, 30; 40, 50, 60; 7, 8, 9]

% One-dimensional String Arrays
strArray = ["Hello", "World", "MATLAB"];
strArray(1) = "Hi";       % Modifies the first element, result is ["Hi", "World", "MATLAB"]
strArray(1:2) = ["Hey", "There"];  % Modifies the first two elements, result is ["Hey", "There", "MATLAB"]

% Multi-dimensional String Arrays
multiStrArray = ["Hello", "World"; "MATLAB", "Programming"];
multiStrArray(1, 2) = "Everyone";  % Modifies the element in the first row, second column, result is ["Hello", "Everyone"; "MATLAB", "Programming"]
multiStrArray(1:2, 1) = ["Hi"; "Hello"];  % Modifies the first column, result is ["Hi", "Everyone"; "Hello", "Programming"]

% One-dimensional Cell Arrays
cellArray = {1, 'MATLAB', [2, 3, 4]};
cellArray{1} = 10;       % Modifies the first element, result is {10, 'MATLAB', [2, 3, 4]}
cellArray{2:3} = {'Hi', [5, 6, 7]}; % Modifies elements from the second to the third, result is {10, 'Hi', [5, 6, 7]}

% Multi-dimensional Cell Arrays
multiCellArray = {1, 'text'; 2, 'more text'; 3, 'even more text'};
multiCellArray{2, 1} = 20;   % Modifies the element in the second row, first column, result is {1, 'text'; 20, 'more text'; 3, 'even more text'}
multiCellArray{2:3, 2} = {'new text', 'latest text'}; % Modifies elements from rows 2 to 3 in column 2, result is {1, 'text'; 20, 'new text'; 3, 'latest text'}

4. Case and Space Sensitivity

MATLAB is case-sensitive, meaning that variable and function names like VariableName and variablename are considered different.

Additionally, MATLAB is somewhat space-sensitive, meaning spaces around operators, assignments, and in-function calls are mostly optional and do not affect code execution. While spaces are generally not significant in MATLAB syntax, improper placement can sometimes cause errors or affect readability. For Example:

     % These are all equivalent
     y = sin(x);
     y=sin(x);
     y = sin( x );

     % Both create the same vector    
     A = [1 2 3];
     A = [1, 2, 3];


     % These are also equivalent
     result = max( a, b );
     result=max(a,b);


     % Each would work with or without spaces    
     a=1; % No spaces
     b = 2; % With spaces
     c = 3 + 4; % With spaces around the operator
     d=3+4; % No spaces around the operator

However, spaces within strings and in the definition of matrices and arrays must be used correctly. For example:

     str1 = 'Hello';
     str2 = 'Hello ';
     isEqual = strcmp(str1, str2); % This will be false because of the trailing space in str2


     rowVec = [1 2, 3, 4 5];  % MATLAB might not interpret this correctly due to mixed delimiters
     rowVec = [1 2   3,4, 5];  % Might still run but is hard to read and maintain

     A = [1 2 3 4 5];  % Consistent use of spaces
     B = [1, 2, 3, 4, 5];  % Consistent use of commas

For more information, see Case and Space Sensitivity

Code Style:

Note that while MATLAB allows for flexible spacing, consistent use of spaces enhances code readability and maintainability. This is especially important in collaborative environments or when sharing code with others.

Adopting a consistent coding style, including the use of spaces, helps in maintaining clean and understandable code. MATLAB's code analyzer provides guidelines and warnings to improve code quality, including spacing issues.

5. Code Suggestions and Completions

MATLAB offers real-time syntax checking and code suggestions. As you type in the Command Window or Editor, MATLAB will suggest function names, variable names, and other elements. MATLAB also indicates matched and mismatched delimiters (e.g., parentheses and brackets) and paired language keywords (e.g., for, if, while, else, and end statements). For more information, see Check Syntax as You Type.

6. Scripts vs Functions

Scripts: Scripts are collections of MATLAB commands executed exactly as if they were typed into the Command Window. They operate within the current workspace, which means they can modify any existing variables or create new ones. Scripts do not accept inputs directly (though they can work with data already in the workspace) and do not return outputs. Scripts are useful for automating a series of MATLAB commands and for writing code that does not need to be modular or reusable, like data manipulation and plotting.

Functions: Functions, on the other hand, are more versatile and encapsulate their code within a separate workspace. They can accept inputs and return outputs, making them essential for modular programming. Functions prevent potential conflicts with the main workspace by keeping variables local, except those explicitly returned. They are ideal for reusing code, enhancing code readability, and managing larger projects where data encapsulation is necessary.

7. Command Cheat Sheet

Command Description
Viewing Elements
who Lists the names of all elements currently in the workspace. Does not display values.
whos Lists all elements in the workspace along with detailed information about each variable, such as size, bytes, class (data type), and attributes. Does not display values.
disp(element) Displays the value of the specified element.
Deleting Elements
clear element Deletes the specified element from the workspace.
clear all Deletes all elements from the workspace.
clearvars varName1 varName2 Deletes specific element from the workspace.
clearvars -except varName1 var2 Deletes all elements from the workspace except the specified ones.
Inspecting Elements
size(element) Returns the dimensions of an array.
length(element) Returns the length of the largest array dimension.
class(element) Returns the class of the element.

8. Suggested Tutorials

Tutorial: Creating and Manipulating Arrays

Tutorial: Accessing Data in Arrays

9. Supplemental Materials

Cheat Sheet: Example of Code Syntax and Formatting

Live Demo: Basic Syntax

Live Demo: Variables Overview

Live Demo: Colon Notation

Live Demo: Matrices

Live Demo: Scripts

Documentation: Matrices and Arrays

Documentation: Create and Run Sections in Code

Documentation: Creating Scripts

Documentation: Scripts

Video: Variables for Numbers, Indexing

Andy's Brain Book: Navigation and Matrices

Next Page
Next Page