Main Content

colon, :

Create symbolic vectors, array subscripting, and for-loop iterators

Description

m:n returns a symbolic vector of values [m,m+1,...,n], where m and n are symbolic constants. If n is not an increment of m, then the last value of the vector stops before n. This behavior holds for all syntaxes.

example

m:d:n returns a symbolic vector of values [m,m+d,...,n], where d is a rational number.

example

x:x+r returns a symbolic vector of values [x,x+1,...,x+r], where x is a symbolic variable and r is a rational number.

example

x:d:x+r returns a symbolic vector of values [x,x+d,...,x+r], where d and r are rational numbers.

example

Examples

Create Numeric and Symbolic Arrays

Use the colon operator to create numeric and symbolic arrays. Because these inputs are not symbolic objects, you receive floating-point results.

1/2:7/2
ans =
    0.5000    1.5000    2.5000    3.5000

To obtain symbolic results, convert the inputs to symbolic objects.

sym(1/2):sym(7/2)
ans =
[ 1/2, 3/2, 5/2, 7/2]

Specify the increment used.

sym(1/2):2/3:sym(7/2)
ans =
[ 1/2, 7/6, 11/6, 5/2, 19/6]

Obtain Increments of Symbolic Variable

syms x
x:x+2
ans =
[ x, x + 1, x + 2]

Specify the increment used.

syms x
x:3/7:x+2
ans =
[ x, x + 3/7, x + 6/7, x + 9/7, x + 12/7]

Obtain increments between x and 2*x in intervals of x/3.

syms x
x:x/3:2*x
ans =
[ x, (4*x)/3, (5*x)/3, 2*x]

Find Product of Harmonic Series

Find the product of the first four terms of the harmonic series.

syms x
p = sym(1);
for i = x:x+3 
    p = p*1/i;
end
p
p =
1/(x*(x + 1)*(x + 2)*(x + 3))	

Use expand to obtain the full polynomial.

expand(p)
ans =
1/(x^4 + 6*x^3 + 11*x^2 + 6*x)	

Use subs to replace x with 1 and find the product in fractions.

p = subs(p,x,1)
p =
1/24

Use vpa to return the result as a floating-point value.

vpa(p)
ans =
0.041666666666666666666666666666667

You can also perform the described operations in a single line of code.

vpa(subs( expand(prod(1./(x:x+3))) ,x,1))
ans =
0.041666666666666666666666666666667

Input Arguments

collapse all

Input, specified as a symbolic constant.

Input, specified as a symbolic constant.

Input, specified as a symbolic variable.

Upper bound on vector values, specified as a symbolic rational. For example, x:x+2 returns [ x, x + 1, x + 2].

Increment in vector values, specified as a symbolic rational. For example, x:1/2:x+2 returns [ x, x + 1/2, x + 1, x + 3/2, x + 2].

Version History

Introduced before R2006a

See Also