Find a Guide

Defining and Manipulating Variables in MATLAB

Types of Variables

There are 4 main types of variables in MATLAB:

  • numbers (double, singles, integers)
  • strings
  • character arrays
  • boolean

There are also NaN values, or 'not a number', but we will touch on those more later! Notice how number variables can be classified as three different subtypes. Integers are whole numbers without any non-zero values after the decimal. As for the difference between single and double values, single values use 32 bits and double values use 64 bits. Single values have less precision than double values due to the number is bits used to store the number's information, and hence, use less storage. For the other 3 variable types, we will use them much more throughout the course.

Defining Variables

Let's work on defining some variables now! Defining variables is quick and easy, and unlike other languages such as C++, we do not have to clarify what type of variables we are defining.

matlab

num = 4;
fl = 1/3;
str = "howdy";
char = 'pizza';
bool = true;
bool_2 = 0;

For variables, we can call them whatever you would like, except they must start with a letter and only contain alphanumeric characters and the underscore character. Here are some examples of variables that would not work.

matlab

% These variables will error!
3taco = "taco";
_pizza = 45;
^dog = "cat";

Case Sensitivity

In MATLAB, all variables are case sensitive! What that means is capitalization matters! Let's look at an example of this.

matlab

pizza = "pizza";
Pizza = "Pizza";
disp(pizza); % output: "pizza"

In the example above, we defined two variables, 'pizza' and 'Pizza'. Now, when we printed the variable 'pizza' to the command window using the function 'disp()', it outputted "pizza" because we used the lowercase variable of the two, so the value associated with the variable was retrieved and printed. So, make sure to double check your variable names!

Manipulating Variables

To overwrite variables, all we have to is assign the variable to a new value. Here is an example of that.

matlab

% Define a variable
num = 5;
num = 8;
disp(num); %output: 8

Removing Variables

Now, what if at some point in our code, we want to remove a variable from our Workspace? Well, we can use the built-in function 'clear'.

matlab

% Taking the variable 'num' from above
clear num % This removes num from the Workspace

Predefined Variables

In MATLAB, there are predefined variables for common values that are often used. Here are some:

matlab

pi; % 3.14159...
true; % logical 1
false; % logical 0
eps; % distance from 1.0 to the next larger double-precision number = 2^(-52)
Find a Guide