Naming Variables in MATLAB
The rules for naming a variable in MATLAB are as follows:
- A variable name must begin with a letter which may be followed by letters, digits, or underscores (no other special character allowed).
- MATLAB is case-sensitive which means that upper and lower case letters are considered different. (‘w3wiki’ and ‘w3wiki’ are considered separate variable names)
- Avoid giving variables the same name as that of existing MATLAB functions.
Examples of valid MATLAB Variable Names
Valid MATLAB Variable Names |
---|
Geeks |
A_bcd |
CoDing2001 |
First_Val |
Examples of valid MATLAB Variable Names
Variable Name | Cause for Invalidity |
---|---|
7Abc | Variable name should always begin with an alphabet |
_Geeks | Variable name should always begin with an alphabet |
end | Variable names should not be the same as already existing MATLAB functions |
Coding!! | Variable names should not have any special characters except underscore |
MATLAB Syntax
Writing code in the MATLAB environment is quite simple. We do not need to include any libraries/header files, we can directly start writing commands in the command window of the Editor. Usually, we write small and easily executable programs in the Command Window and larger programs with multiple lines and functions in the Editor.
Now, we will see the syntax of a MATLAB program. Let us begin with the very basic code to display ‘Hello World’ as the output in the command window:
Example:
Matlab
% A MATLAB program illustrate % disp function disp( "Hello World" ) |
Here, disp() is a function used to display the desired value as the output.
Output:
Likewise, we can perform any basic operation in the command window. Let’s have a look at a few of them.
Example :
Matlab
% Adding two numbers in the % MATLAB Command Window 15 + 25 |
Output :
In the above output, ‘ans’ is a default variable in MATLAB that stores the value of the most recent output. This variable is only created when output is generated without any specific argument to it.
Example:
Matlab
% MATLAB code for multiplying two numbers % in MATLAB Command Window 20 * 5 |
Output :
Thus, we can perform various mathematical operations in the MATLAB command window. The following table summarizes the various operations along with their syntax that can be performed in MATLAB:
Sr. No. | Operator | Operation | Sample Input | Sample Output |
---|---|---|---|---|
1. | + | Addition | 20 + 30 | 50 |
2. | – | Subtraction | 20 – 30 | -10 |
3. | * | Multiplication | 20 × 30 | 600 |
4. | ^ | Exponentiation | 2 ^ 3 | 8 |
5. | \ | Left-division operator. | 10\5 | 0.5000 |
6. | / | Right-division operator. | 10/5 | 2 |