BudiBadu Logo
Samplebadu

MATLAB by Example: Variables

R2023b

Variables in MATLAB are created by assignment. This sample demonstrates how to define variables and suppress output.

Code

% Assigning a value to a variable
x = 10; % Semicolon suppresses output

% Variables are case sensitive
X = 25;

% Basic arithmetic
y = x + 5;

% Displaying values
disp(y)

% Predefined constants
pi_val = pi;
inf_val = Inf;
nan_val = NaN;

% String variables
name = "MATLAB";
message = 'Hello World';

Explanation

In MATLAB, you create variables simply by assigning a value to a name using the equals sign =. Unlike statically typed languages, you do not need to declare the type of the variable; MATLAB automatically determines it based on the assigned value. Variable names must start with a letter and can contain letters, digits, and underscores, but they are case-sensitive, so x and X are distinct variables.

One of the most distinctive features of the MATLAB command line is the use of the semicolon ;. If you end a statement with a semicolon, MATLAB performs the computation but suppresses the output to the Command Window. If you omit the semicolon, the result is immediately displayed. This is useful for debugging or interactive exploration but is usually suppressed in scripts to keep the output clean.

MATLAB includes several built-in constants that are useful for mathematical computations. pi returns the floating-point approximation of $pi$, Inf represents infinity (often the result of dividing by zero), and NaN stands for "Not a Number" (the result of undefined operations like 0/0). Strings can be defined using either double quotes "..." (string arrays) or single quotes '...' (character vectors).

Code Breakdown

2
x = 10; assigns 10 to x. The semicolon prevents "x = 10" from being printed to the console.
11
disp(y) explicitly displays the value of y.