0
0
MATLABdata~5 mins

Colon operator for ranges in MATLAB

Choose your learning style9 modes available
Introduction
The colon operator helps you create lists of numbers quickly and easily without typing each number.
When you want to create a sequence of numbers from 1 to 10.
When you need to pick every second number between 2 and 20.
When you want to loop through a range of values in a for-loop.
When you want to select parts of a matrix using row or column ranges.
Syntax
MATLAB
start:step:end
If you leave out 'step', it assumes 1 by default.
The range includes 'start' and goes up to 'end' without passing it.
Examples
Creates numbers from 1 to 5 with step 1: [1 2 3 4 5]
MATLAB
1:5
Creates numbers from 2 to 10 with step 2: [2 4 6 8 10]
MATLAB
2:2:10
Creates numbers from 5 down to 1 with step -1: [5 4 3 2 1]
MATLAB
5:-1:1
Sample Program
This program creates two ranges: one counting up from 1 to 5, and one counting down from 10 to 2 by twos, then displays them.
MATLAB
range1 = 1:5;
range2 = 10:-2:2;
disp('Range 1:');
disp(range1);
disp('Range 2:');
disp(range2);
OutputSuccess
Important Notes
If the step size does not fit exactly, the range stops before passing the end value.
Using a negative step lets you count backwards.
The colon operator is very useful for indexing parts of arrays or matrices.
Summary
The colon operator creates sequences of numbers easily.
You can specify start, step, and end values.
It works for counting up or down.