Kahibaro
Discord Login Register

MATLAB Syntax and Expressions

Introduction

MATLAB has its own language with rules about how to write commands, how to combine numbers and variables, and how to form expressions that MATLAB can evaluate. In this chapter you will focus on the basic structure of MATLAB language syntax and how expressions are formed and executed. You will see how MATLAB reads what you type, how lines are separated, how results are displayed or suppressed, and how MATLAB evaluates arithmetic and more general expressions.

Commands, Statements, and Expressions

In MATLAB a single instruction that you type and execute is called a statement. Many statements contain expressions. An expression is anything that MATLAB can evaluate to produce a value, for example 2+3, sin(pi/4) or x^2 + 3*x + 1 after x has been defined.

Every statement is usually written on one line and is terminated when you press Enter. MATLAB immediately evaluates the statement in the Command Window or when that line is reached inside a script or function. Simple examples are:

2 + 3
cos(0)
1 + 2 * 3

In each case MATLAB computes the value of the expression and, if you do not tell it otherwise, displays the result.

The basic pattern of a MATLAB statement is:

expression

or, when you store the result in a variable, it becomes an assignment which you will study in detail in a later chapter. For now, it is enough to observe that MATLAB first evaluates the expression on the right hand side, then stores it:

result = 2 + 3 * 4

Here 2 + 3 4 is the expression. result = 2 + 3 4 is the full statement.

Displaying and Suppressing Output

By default when you execute an expression as a statement, MATLAB displays the result in the Command Window. For example, entering:

3^2

will display the answer in a variable named ans. The special variable ans is automatically created or updated when you evaluate an expression without assigning the result to a named variable.

If you add a semicolon at the end of a statement, MATLAB still evaluates it but does not display the result. This is called suppressing output:

3^2;

In this case MATLAB computes the value but does not show it. The semicolon is not part of the mathematical expression. It is part of the MATLAB statement syntax that controls display behavior.

This behavior is the same whether or not you use an assignment. For example:

x = 10      % result is displayed
y = 20;     % result is not displayed

Using semicolons becomes especially important in scripts and when working with large arrays, so that the Command Window is not flooded with long outputs.

Line Endings and Multiple Statements on a Line

Pressing Enter normally ends the statement on the current line. MATLAB reads that line, evaluates it, and then waits for the next line. Sometimes you may want to write more than one statement on the same line. MATLAB allows multiple statements on a single line if you separate them with commas or semicolons.

For example:

a = 2; b = 3; c = a + b

In this single line there are three statements. The first two have semicolons at the end so their outputs are suppressed. The last one has no semicolon so MATLAB displays the value of c.

A comma also separates statements but does not suppress display:

x = 5, y = 6

This executes x = 5 then displays x, then executes y = 6 and displays y. In practice semicolons are more common than commas in this role because they keep the output tidy.

Continuing Long Lines

Sometimes an expression is too long to fit comfortably on one line or you want to split it to make it easier to read. MATLAB lets you continue a statement on the next line by using three dots followed by optional spaces. These three dots are called the line continuation operator.

For example:

value = 1 + 2 + 3 + 4 + 5 + 6 + ...
        7 + 8 + 9 + 10;

Here MATLAB treats the two physical lines as one logical statement. You can use line continuation with any long expression, including function calls with many arguments.

You do not need continuation dots when you break inside some syntactic forms, such as within brackets when creating arrays. However, the three dots always work and make your intent clear.

Arithmetic Operators and Operator Precedence

MATLAB follows familiar arithmetic rules for interpreting expressions with multiple operators. These rules are controlled by operator precedence. Operators with higher precedence are applied before those with lower precedence, unless you use parentheses to change the order manually.

For basic arithmetic expressions MATLAB uses:

  1. Parentheses ( and ) to explicitly group parts of an expression.
  2. Exponentiation ^.
  3. Unary plus and minus, such as -x or +x, which apply to a single operand.
  4. Multiplication * and division / and \.
  5. Addition + and subtraction -.

For example, in the expression

1 + 2 * 3^2

MATLAB first computes 3^2 to get 9, then 2 * 9 to get 18, then adds 1 to get 19.

If you want a different order, you use parentheses:

(1 + 2) * 3^2      % gives 27
(1 + 2 * 3)^2      % gives 49

Parentheses are part of the expression syntax and you can nest them as deeply as needed, as long as they are properly matched.

Besides these arithmetic operators there are others such as relational and logical operators, which have their own precedence. You will study them in a later chapter that focuses on logical expressions.

MATLAB Names, Case Sensitivity, and Keywords

When you start to write nontrivial expressions, you will often involve named quantities. These names must follow MATLAB rules.

Every name you use for variables or functions must start with a letter, followed by letters, digits, or underscores. You cannot start a name with a digit or a symbol like + or -. For example, data1, x_value, and Rate2 are valid names. 1data or x-value are not valid.

MATLAB is case sensitive. This means that Result, result, and RESULT are three different names from MATLAB's point of view. When you use a name in an expression it must match exactly the case used when you defined it.

Some words are reserved as MATLAB keywords. These are part of the language itself and cannot be used as variable names. Examples include if, for, while, function, and several others. If you try to use a keyword as a name, MATLAB will produce an error or unexpected behavior.

MATLAB also has many built in function names such as sin, plot, or mean. Technically you can create a variable with the same name, but doing so can hide the function and is usually a bad idea. For example, if you do:

sin = 3;

then later type sin(pi/2), MATLAB will not call the sine function because sin now refers to a number. A good habit is to avoid variable names that match known function names.

Using Parentheses for Grouping and Function Calls

Parentheses have two important syntactic roles in MATLAB expressions. The first role is grouping, which you have already seen. You can write:

total = (a + b) * c;

Here parentheses control the order of operations.

The second role is to mark function calls and enclose function input arguments. A simple function call looks like this:

result = sqrt(16)

The function name comes first, followed by parentheses that contain a comma separated list of arguments. Even if there is just one argument, as in this example, you still write it inside parentheses.

You can combine both roles. An expression such as:

y = sin(2 * pi * t);

calls the function sin with the argument 2 pi t. Within that argument, parentheses around 2 pi t would act as grouping if you choose to add them. Here the necessary grouping is already controlled by operator precedence.

When MATLAB reads a name followed directly by parentheses, it interprets that as a function call. When it reads the same name without parentheses, it interprets it as a variable or constant in an expression.

Literal Numbers and Basic Numeric Expressions

In MATLAB you can type numbers directly into expressions. These are called numeric literals. You can write integers such as 5 or -12, and real numbers with decimal points such as 3.14 or 0.001.

MATLAB also supports scientific notation using the letter e or E. For example:

x = 1e3    % 1000
y = 5.2e-2 % 0.052

This notation is especially convenient when you work with very large or very small values.

You can combine literal numbers freely with operators and functions in expressions. For example:

value = 2.5 * 1e3 - 7 / 4

MATLAB evaluates this by following the usual precedence rules.

You can also write complex literals by combining real and imaginary parts using i or j as the imaginary unit:

z = 3 + 4i

Complex numbers are an important part of MATLAB, but their detailed use belongs to a later chapter. At this stage it is enough to recognize that i or j in a numeric context can indicate an imaginary part.

Combining Functions and Nested Expressions

MATLAB expressions often involve calling several functions and combining their results. You can nest function calls inside one another and include them as subexpressions.

For example:

y = log10(1 + sqrt(3))

This is a single expression. MATLAB first computes sqrt(3), then adds 1, then applies log10 to the result. Parentheses show which arguments belong to which function and determine the nesting.

You can also use the output of one function as part of a larger arithmetic expression:

t = 0.5;
x = exp(-t) * cos(2 * pi * t);

Here exp and cos are both functions. Their outputs are multiplied to form x.

While you can nest function calls deeply, readability becomes important. You can always break a complex expression into several simpler statements without changing the mathematics, for example:

u = sqrt(3);
v = 1 + u;
y = log10(v);

The expression is the same, but it is spread across several lines.

Comments and Ignored Text in Expressions

Alongside expressions you often want to include explanations for yourself or others. In MATLAB you write comments that MATLAB ignores when evaluating expressions.

A comment starts with the percent symbol % and continues to the end of the line. Everything from % onward is not executed. For example:

x = 2 + 3   % add 2 and 3 and store in x

The expression here is 2 + 3. The comment is add 2 and 3 and store in x. MATLAB evaluates the expression and ignores the comment.

You can also have a line that is only a comment:

% This line explains what the next section of code does

Comments are not part of the expression syntax itself, but they can appear to the right of an expression or statement on the same line. They cannot appear in the middle of a number or name.

Automatic Variable ans

When you type an expression as a statement without assigning it to a variable, MATLAB stores its result in a special variable called ans. For example, if you enter:

2 + 3

MATLAB displays the output and also stores it in ans. You can then use ans in later expressions:

ans * 4

This multiplies the previous result by 4.

Although ans can be convenient for quick one off calculations, relying on it in longer expressions can make your code hard to read and understand. It is usually clearer to assign the result to a named variable instead.

Common Syntax Errors in Expressions

When you begin writing MATLAB expressions, a few kinds of mistakes happen frequently. Recognizing them as syntax errors helps you understand MATLAB's error messages.

A missing parenthesis is a very common problem. If you start with ( you must close it with a matching ). An expression like:

y = (1 + 2 * 3;

has one extra ( or one missing ) and MATLAB will complain about an unexpected end of input or a missing parenthesis.

Another frequent error is using an invalid name, for example:

1stValue = 10;

Here the name starts with a digit. MATLAB will report an invalid expression or unexpected character at that position.

You may also accidentally type an operator in a place where MATLAB expects something else. For example:

x = 2 + * 3;

This expression is not well formed and MATLAB will report a syntax error near *. Whenever you see an error like this, look around the indicated position in the line and check that every operator has an operand on both sides and parentheses are balanced.

Sometimes you might forget a line continuation when you intend to spread an expression across multiple lines. If MATLAB shows an error at the start of a new line that you meant to be a continuation, add ... at the end of the previous line so that MATLAB treats the entire expression as one statement.

Important points to remember:
MATLAB evaluates expressions according to operator precedence, but you can always control the order with parentheses.
A semicolon at the end of a statement suppresses displaying the result, while a comma separates statements without suppressing output.
Names are case sensitive and must start with a letter, and you should avoid using MATLAB keywords or function names as variable names.
Use ... to continue a long statement on the next line, and % to add comments that MATLAB ignores.
When you enter an expression without assigning it, MATLAB stores the result in ans, but for clearer code prefer explicit variable names.

Views: 5

Comments

Please login to add a comment.

Don't have an account? Register now!