Lesson 2

Basic syntax


Now that you have a grip on the basics, we're going to dive deeper into the following areas:

  1. Variables and variable definition

  2. MATLAB as a calculator

  3. Data types and formats

  4. Operators and special characters

  5. Adding comments to your code

  6. User input from the keyboard

  7. Displaying the variable as output

Variables and variable definition

Variables are used to store information in memory and give it a special label.

You can define variables using the assignment operator (=). Note that MATLAB variables can be assigned without declaring their type, and that the type can change during the execution of your program. Below is an example of how you'd declare a variable called n and give it a value of 10:

In the above code snippet, MATLAB will actually create a 1×11\times 1 matrix under the hood (since it's a Matrix Language). If you don't give your variable a name, it will automatically be assigned to the default one called ans:

Note: A valid variable name in MATLAB starts with a letter, and can be followed by letters, digits or underscores (_). Remember that MATLAB is case-sensitive, so A and a are not the same variable!

MATLAB as a Calculator

The MATLAB environment is pretty much like a super smart calculator, and can perform all the mathematical operations that you're used to doing in school.

It's also what's known as an interpreted environment, which means that you can give it any command in the command window, and it will be executed it right away.

Let's see how it works! Type a valid mathematical expression, for example:

When you press "enter", MATLAB executes it immediately and the result of your operation is returned:

Here's another more complex example:

You can also solve real world mathematical problems. For example, let's calculate the number of of seconds in the month of January.

We know that January has 3131 days, each day has 2424 hours, each hour has 6060 minutes and each minute has 6060 seconds. In the MATLAB command window, we can define variables for all of these values and make it easy for anyone to follow the logic of our program:

Notice how defining variables makes your program much easier to read?

Compare that to a program with a single line:

Use this example as a reminder that your program isn't always better just because it's shorter.

Data types

When working on a program, it's always important to keep track of the data type of your variables, or else you might end up with unexpected results!

As an example, if you add two integers together (2 + 2), the result is 4, but if you add two (seemingly identical) numbers which are actually strings ("2" + "2"), the result will be "22"!

Let's first go through the different types of numbers that exist in MATLAB:

And here are the available data types that you can use to store them:

As we saw earlier, the reason why these data types are so important is because the result of your operation sometimes depends on how precise you want to be.

Consider the following product 23.5*19.234. The correct result of this operation is 451.999. This works fine when we use the single and double data types:

But notice how we lose precious data if we use other data types:

As you can see, integer data types (like int16 and int32) can only handle whole numbers, which explains why their result is 452452 instead of 451.999451.999.

int8 is worse, since it can't even handle a number that big, so it just displays its maximum value (127127).

Now let's move on to text values. Strings and characters are declared by typing the character in single quotes ('). Here's an example of how you can define a student's name and grade:

It's important to note that all characters in MATLAB have an equivalent numerical value based on the American Standard Code for Information Interchange (also known as "ASCII"). This is what programmers call "encoding". For example, the name James King in MATLAB is actually a vector with 10 elements in it (including the space) as shown below:

From this, you can see that J uses the ASCII code 74, a uses 97, m uses 109, and so on and so forth... Pretty cool!


The format of your output is controlled by the format command which can be used both in line spacing and numerical formats.

You might have noticed in the previous example that the command window contains blank lines in between the execution lines. This is called loose format and is the default option that's used to make the output more readable. If you want to remove this default behaviour, you can use the compact format instead:

For the numeric variables, there are a number of format styles used to display the output.

Operators and Special Characters

An operator is a symbol that tells the compiler to perform a specific mathematical or logical manipulation. The most common operators in MATLAB are:

  • Arithmetic Operators (addition, subtraction, multiplication... etc)

  • Logical Operators (if, else, true, false... etc)

  • Relational Operators (greater than, less than... etc)

MATLAB arithmetic operations can be subdivided into matrix arithmetic operations and array arithmetic operations.

The matrix arithmetic operations are as defined in linear algebra (+,-,*,/,^):

Array operators use the . symbol, and we'll look into them more closely in the next chapter.

Just like artithmetic operators, relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and return a logical array of the same size.

The logical operators can be either element-wise logical operators (operate element-by-element on logical arrays) e.g. &,| and ~ or short-circuit logical operators e.g. && and ||.

Operators in MATLAB have the same order of precedence as in standard linear algebra. Below is a list from the "most important" operator to the least:

  1. Parentheses ()

  2. Transpose , power .^, complex conjugate transpose ´, matrix power ^

  3. Power with unary minus.-, unary plus .+, or logical negation ~ as well as matrix power with unary minus ^-, unary plus ^+, or logical negation ^~

  4. Unary plus +, unary minus -, logical negation ~

  5. Multiplication .*, right division ./, left division .\, matrix multiplication *, matrix right division /, matrix left division \

  6. Addition +, subtraction -

  7. Colon operator :

  8. Less than <, less than or equal to<=, greater than> , greater than or equal to >=, equal to==, not equal to ~=

  9. Element-wise AND &

  10. Element-wise OR |

  11. Short-circuit AND &&

  12. Short-circuit OR ||

There are also special characters that change the format of the display of code or the output in the command window. The table below summarizes the commonly used characters or symbols.

From the example on calculating the seconds in the month in January, every execution is displayed as an output. This can be suppressed by the semi-colon as shown below:

Adding comments to your code

Comment are used to make the code understandable. It makes it easier for the code users to quickly get an idea of what the program is actually doing, and it's usually considered a good practice to add comments to your code.

To put a comment within a line, type % followed by the comment text. MATLAB compiler treats all the information after the % on a line as a comment. For a lengthy comment that results in the the group of lines, type %{ before the first line and %} after the last line you want to comment. For example:

User inputs from the Keyboard

The command we have dealt with required us to assign the number/string or constant to the variables when we initialized them. We can however, prompt the user to input the values to the variable from the keyboard in MATLAB using the function input(). The syntax is x = input(prompt).Whenever this command is executed, the text in prompt is displayed and waits for the user to input a value. This commands are best implemented in a script. We will solve the problem that asks us to compute the seconds in the month of January using the script code_two_0 below ( as keyed in in the command editor)

When the script code_two_0 is run the on the command window the user is prompted to key in the values to the days, hours, mins and secs. before the answer is calculated as shown below.

Displaying the variable as Output

From the previous example, the answer 2678400 is not clearly presented. One can't be able to tell what is it. It is just a numerical figure to many who have no idea about pr0graming. MATLAB has inbuilt functions, disp() or fprintf() to display output to the screen (command window).

The disp() function is the easiest to use but it has limited control of output formatting. It displays exactly one value/variable to the screen on one or more lines.This function is convenient for displaying vectors, matrices, and complex numbers . It display the entire variable within a single function call. In general, use disp() when you do not care about the exact format of the outputFor example

All the commands in code_two_0 script on number of seconds in January,can be suppressed by the semicolon and the final answer displayed using dips() as shown. Save this script as code_two_1

The output in the command window when code_two_1 is run is

The fprintf() function is more complex but it allows you precise control over the output formatting. It can receive one or more arguments. Its syntax is fprintf(str,variable_list)

The first argument, str, usually format string (should be in quotes). The format string should contain a format specifier/descriptor for each variable in variable_list. A format descriptor starts with the special character %, followed by an integer giving the width of the field to be printed.

The fieldWidth - is an integer that specifies how many spaces (or decimal points) to use for the value. In the format string, special escape sequences are used to represent "non-printable" characters. This special escape sequences, begin with the backslash '\' character. Each variable in the variable_list must point to the corresponding specifier. For example,

The format sprint allows the user to add additional text that will help describe the output further. In code_two_1 replace the thedisp() function withfprintf() function and save the script as code_two_2 as shown below

The output in the command window when code_two_2 is run is

Another example (in command window directly), If John bought three books, at $100 each. Let us write MATLAB commands to calculate and display the total cost John incurred.


Part A: Math

Matlab makes an excellent calculator. Try entering some basic math expressions at the prompt in the command window:

Note: The last command gives the remainder when the first value is divided by the second value i.e. 89 divide by 11

Part B: Scripts

1. Write a script in in Matlab, to compute the number of seconds in a leap year. Form your output using the method learned in this chapter.

2. Write a script in Matlab to display the bio data of a student. The script should prompt the user to input the student' surname, age, admission number, class, weight, height and display the result in the command window.



Be the first to comment!