Academic Block

Logo of Academicblock.net

Variables and Constants in MATLAB

Variables and constants are fundamental concepts in MATLAB programming. They allow storing and managing data for various calculations and operations.

Basic Concepts

In MATLAB, variables are containers for storing data. You can create variables without explicitly declaring their type. Constants are fixed values that do not change during execution.

% Creating variables
x = 10;
y = 20.5;
z = 'Hello';
disp(x); disp(y); disp(z);

To define constants, you typically use fixed values directly in calculations or assign them to variables:

% Defining constants
PI = 3.14159;
G = 9.8;
disp(PI); disp(G);

Common Operations with Variables

Arithmetic Operations

Performing arithmetic operations using variables:

% Arithmetic operations
a = 15;
b = 4;
sum = a + b;
product = a * b;
division = a / b;
disp(sum); disp(product); disp(division);

Explanation: Variables a and b are used in arithmetic operations to calculate the sum, product, and division.

Updating Variables

Variables can be updated using new values or expressions:

% Updating variables
x = 10;
x = x + 5; % Increment by 5
disp(x); % Output: 15

Using Constants in Expressions

Constants can be directly used in expressions for calculations:

% Using constants
radius = 5;
area = PI * radius^2; % Area of a circle
disp(area); % Output: 78.53975

Variable Naming Rules

MATLAB variables follow these naming conventions:

  • Must start with a letter.
  • Can contain letters, digits, and underscores (_).
  • Case-sensitive (e.g., Var and var are different).
  • Cannot use reserved keywords (e.g., if, for, break, elseif). You can get the complete list of “reserved keywords” by entering iskeyword command in the workspace.

Example of valid and invalid variable names:

% Valid variable names
var1 = 10;
_temp = 20;
Area = 15;
disp(var1); disp(_temp); disp(Area);

Useful MATLAB Functions

Function
Explanation
who
Displays the list of currently defined variables.
whos
Displays detailed information about the variables.
clear
Removes variables from memory.
isvarname
Checks if a string is a valid variable name.
exist
Checks if a variable, file, or function exists.

Practice Questions

Test Yourself

1. Create a variable x, assign it the value 20, and then update it to x + 10.

2. Define a constant for the gravitational constant G = 9.8 and calculate the force for a mass of 5 kg.

3. Write a script to calculate the area of a rectangle with a given length and width stored in variables.