Beginner

Variables and Types in MATLAB

Learn about variables, data types, and type conversions in MATLAB with practical Docker-ready examples using GNU Octave

MATLAB’s type system reflects its origins as a matrix laboratory. Every value is fundamentally an array—a scalar is a 1x1 matrix, a string is a 1xN character array, and even a boolean is a 1x1 logical array. This array-first design means that operations you write for single values automatically extend to entire matrices without loops.

MATLAB is dynamically typed, so you never declare a variable’s type. You assign a value and MATLAB figures out the rest. It’s also weakly typed in the sense that numeric types mix freely—MATLAB will silently promote an integer to a double when arithmetic demands it. This makes exploratory computation fast but means you need to be aware of what types your variables actually hold.

In this tutorial, you’ll learn how MATLAB handles variables and assignments, explore the built-in numeric, string, and logical types, work with arrays and cell arrays, and see how type conversions work in practice.

Variable Basics and Numeric Types

MATLAB variables are created by simple assignment. There are no declaration keywords—just pick a name and assign a value. Variable names are case-sensitive, must start with a letter, and can contain letters, digits, and underscores.

Create a file named variables.m:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
% Variable assignment - no keywords needed
x = 42;
pi_approx = 3.14159;
name = 'MATLAB';
is_ready = true;

% Check types with class()
fprintf('x: %d (%s)\n', x, class(x));
fprintf('pi_approx: %.5f (%s)\n', pi_approx, class(pi_approx));
fprintf('name: %s (%s)\n', name, class(name));
fprintf('is_ready: %d (%s)\n', is_ready, class(is_ready));

fprintf('\n');

% Numeric types - doubles are the default
a = 10;                 % double (default for all numeric literals)
b = int32(10);          % explicit 32-bit integer
c = uint8(255);         % unsigned 8-bit integer
d = single(3.14);       % 32-bit float

fprintf('=== Numeric Types ===\n');
fprintf('a = %d (%s) - default is double\n', a, class(a));
fprintf('b = %d (%s)\n', b, class(b));
fprintf('c = %d (%s)\n', c, class(c));
fprintf('d = %.2f (%s)\n', d, class(d));

fprintf('\n');

% Special numeric values
fprintf('=== Special Values ===\n');
fprintf('Infinity: %f\n', Inf);
fprintf('Negative infinity: %f\n', -Inf);
fprintf('Not a number: %f\n', NaN);
fprintf('Machine epsilon: %.15e\n', eps);
fprintf('Largest double: %.6e\n', realmax);
fprintf('Smallest positive double: %.6e\n', realmin);

fprintf('\n');

% Complex numbers - built-in support
z1 = 3 + 4i;
z2 = complex(1, -2);

fprintf('=== Complex Numbers ===\n');
fprintf('z1 = %s\n', num2str(z1));
fprintf('z2 = %s\n', num2str(z2));
fprintf('Real part of z1: %.1f\n', real(z1));
fprintf('Imaginary part of z1: %.1f\n', imag(z1));
fprintf('Magnitude of z1: %.1f\n', abs(z1));

fprintf('\n');

% Logical (boolean) values
fprintf('=== Logical Values ===\n');
flag1 = true;
flag2 = false;
flag3 = logical(1);
fprintf('true: %d (%s)\n', flag1, class(flag1));
fprintf('false: %d (%s)\n', flag2, class(flag2));
fprintf('logical(1): %d (%s)\n', flag3, class(flag3));
fprintf('5 > 3 produces: %d (%s)\n', 5 > 3, class(5 > 3));

Arrays, Strings, and Composite Types

In MATLAB, every variable is an array. Understanding how arrays, character arrays, cell arrays, and structs work is essential because these are the building blocks you’ll use for everything.

Create a file named variables_types.m:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
% Character arrays vs strings
fprintf('=== Character Arrays ===\n');
char_arr = 'Hello';
fprintf('char_arr: %s (%s, size: %dx%d)\n', char_arr, class(char_arr), size(char_arr, 1), size(char_arr, 2));
fprintf('char_arr(1): %s (ASCII: %d)\n', char_arr(1), char_arr(1));

fprintf('\n');

% Matrices - the core data structure
fprintf('=== Matrices ===\n');
row_vec = [1, 2, 3, 4, 5];
col_vec = [1; 2; 3; 4; 5];
matrix = [1, 2, 3; 4, 5, 6; 7, 8, 9];

fprintf('Row vector: ');
fprintf('%d ', row_vec);
fprintf('(size: %dx%d)\n', size(row_vec, 1), size(row_vec, 2));

fprintf('Column vector: ');
fprintf('%d ', col_vec);
fprintf('(size: %dx%d)\n', size(col_vec, 1), size(col_vec, 2));

fprintf('Matrix (3x3):\n');
disp(matrix);

% A scalar is just a 1x1 matrix
scalar = 42;
fprintf('Scalar %d has size: %dx%d\n', scalar, size(scalar, 1), size(scalar, 2));

fprintf('\n');

% Cell arrays - heterogeneous containers
fprintf('=== Cell Arrays ===\n');
mixed = {42, 'hello', 3.14, true, [1, 2, 3]};
fprintf('Cell array contents:\n');
for i = 1:length(mixed)
    val = mixed{i};
    fprintf('  mixed{%d}: %s (%s)\n', i, num2str(val), class(val));
end

fprintf('\n');

% Structs - named fields
fprintf('=== Structs ===\n');
point.x = 3.0;
point.y = 4.0;
point.label = 'origin';
fprintf('point.x = %.1f\n', point.x);
fprintf('point.y = %.1f\n', point.y);
fprintf('point.label = %s\n', point.label);
fprintf('Fields: ');
fields = fieldnames(point);
fprintf('%s ', fields{:});
fprintf('\n');

fprintf('\n');

% Type conversions
fprintf('=== Type Conversions ===\n');

% Numeric conversions
int_val = int32(3.7);
fprintf('int32(3.7) = %d (rounds to nearest)\n', int_val);

double_val = double(int32(42));
fprintf('double(int32(42)) = %.1f\n', double_val);

% String to number
num_from_str = str2double('123.45');
fprintf('str2double(''123.45'') = %.2f (%s)\n', num_from_str, class(num_from_str));

% Number to string
str_from_num = num2str(42);
fprintf('num2str(42) = ''%s'' (%s)\n', str_from_num, class(str_from_num));

% Logical conversions
fprintf('logical(0) = %d, logical(1) = %d\n', logical(0), logical(1));
fprintf('double(true) = %.1f\n', double(true));

fprintf('\n');

% Constants - MATLAB uses conventions, not a const keyword
fprintf('=== Constants (by Convention) ===\n');
MAX_ITERATIONS = 1000;
GRAVITY = 9.81;
fprintf('MAX_ITERATIONS = %d\n', MAX_ITERATIONS);
fprintf('GRAVITY = %.2f\n', GRAVITY);
fprintf('Built-in pi = %.10f\n', pi);
fprintf('Built-in i (imaginary unit) = %s\n', num2str(1i));

fprintf('\n');

% Checking for empty and special values
fprintf('=== Empty and Special Values ===\n');
empty_arr = [];
fprintf('Empty array size: %dx%d\n', size(empty_arr, 1), size(empty_arr, 2));
fprintf('isempty([]): %d\n', isempty(empty_arr));
fprintf('isnan(NaN): %d\n', isnan(NaN));
fprintf('isinf(Inf): %d\n', isinf(Inf));
fprintf('isnumeric(42): %d\n', isnumeric(42));
fprintf('ischar(''hello''): %d\n', ischar('hello'));
fprintf('islogical(true): %d\n', islogical(true));

Running with Docker

1
2
3
4
5
6
7
8
# Pull the GNU Octave image
docker pull gnuoctave/octave:9.4.0

# Run the basics example
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system variables.m

# Run the types example
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system variables_types.m

Expected Output

Output from variables.m:

x: 42 (double)
pi_approx: 3.14159 (double)
name: MATLAB (char)
is_ready: 1 (logical)

=== Numeric Types ===
a = 10 (double) - default is double
b = 10 (int32)
c = 255 (uint8)
d = 3.14 (single)

=== Special Values ===
Infinity: Inf
Negative infinity: -Inf
Not a number: NaN
Machine epsilon: 2.220446049250313e-16
Largest double: 1.797693e+308
Smallest positive double: 2.225074e-308

=== Complex Numbers ===
z1 = 3+4i
z2 = 1-2i
Real part of z1: 3.0
Imaginary part of z1: 4.0
Magnitude of z1: 5.0

=== Logical Values ===
true: 1 (logical)
false: 0 (logical)
logical(1): 1 (logical)
5 > 3 produces: 1 (logical)

Output from variables_types.m:

=== Character Arrays ===
char_arr: Hello (char, size: 1x5)
char_arr(1): H (ASCII: 72)

=== Matrices ===
Row vector: 1 2 3 4 5 (size: 1x5)
Column vector: 1 2 3 4 5 (size: 5x1)
Matrix (3x3):
   1   2   3
   4   5   6
   7   8   9

Scalar 42 has size: 1x1

=== Cell Arrays ===
Cell array contents:
  mixed{1}: 42 (double)
  mixed{2}: hello (char)
  mixed{3}: 3.14 (double)
  mixed{4}: 1 (logical)
  mixed{5}: 1  2  3 (double)

=== Structs ===
point.x = 3.0
point.y = 4.0
point.label = origin
Fields: x y label 

=== Type Conversions ===
int32(3.7) = 4 (rounds to nearest)
double(int32(42)) = 42.0
str2double('123.45') = 123.45 (double)
num2str(42) = '42' (char)
logical(0) = 0, logical(1) = 1
double(true) = 1.0

=== Constants (by Convention) ===
MAX_ITERATIONS = 1000
GRAVITY = 9.81
Built-in pi = 3.1415926536
Built-in i (imaginary unit) = 0+1i

=== Empty and Special Values ===
Empty array size: 0x0
isempty([]): 1
isnan(NaN): 1
isinf(Inf): 1
isnumeric(42): 1
ischar('hello'): 1
islogical(true): 1

Key Concepts

  • Everything is an array: A scalar is a 1x1 matrix, a string is a 1xN character array. This array-first design means operations naturally extend from scalars to matrices.
  • Doubles by default: Every numeric literal is a double unless you explicitly cast it with int32(), uint8(), single(), etc.
  • Dynamic and weakly typed: No type declarations needed. MATLAB freely converts between numeric types during arithmetic, promoting to double when needed.
  • class() reveals the type: Use class(x) to check any variable’s type, and whos in the interactive workspace to see all variables with their sizes and types.
  • Cell arrays for mixed types: Regular arrays require all elements to be the same type. Cell arrays ({}) can hold any mix of types—numbers, strings, other arrays, even other cell arrays.
  • Structs for named data: Use dot notation (point.x = 3.0) to create structured data with named fields, similar to dictionaries in other languages.
  • No const keyword: MATLAB relies on naming conventions (UPPER_CASE) to signal constants. Built-in constants like pi, Inf, NaN, and eps are predefined.
  • Type-checking functions: MATLAB provides isnumeric(), ischar(), islogical(), isempty(), isnan(), and isinf() to inspect values at runtime.

Running Today

All examples can be run using Docker:

docker pull gnuoctave/octave:9.4.0
Last updated:

Comments

Loading comments...

Leave a Comment

2000 characters remaining