Beyond making it easy to deal with a large amount of data succintly, array operations allow a compiler to make optimizations that a loop-based operation won't allow.
>> x = 1:5 x = 1 2 3 4 5 >>You don't have to start with 1: try "x = -7:12". Equally interesting, you don't have to use integers:
>> x = 0.1:5
x =
0.1000 1.1000 2.1000 3.1000 4.1000
>>
Note that by default the colon notation returns a row vector.
But you know how to change that into a column vector, right?
>> x = 1:2:8
x =
1 3 5 7
>>
The stride need not be positive, or even integer-valued:
>> x = 5:-0.4:1
x =
Columns 1 through 7
5.0000 4.6000 4.2000 3.8000 3.4000 3.0000 2.6000
Columns 8 through 11
2.2000 1.8000 1.4000 1.0000
>>
Notice that when Matlab has to split a long row vector across lines, it
gives you the column numbers above each line. Now note what happens
when you try:
>> x = 1:-1:5 x = Empty matrix: 1-by-0 >>Empty matrices are both useful and irritating in Matlab. When you program a loop in most languages with a positive increment and upper bound smaller than the lower bound, the loop is skipped. With Matlab colon notation, you get something: empty, but still with a well-defined size.
Most of these indexing examples seem stupid, and generally they are. Where you will end up using the indexing is where the start:stride:last triplet comes from program parameters, e.g.,
x(k:lda:n)(and yes, that is a real examples from a code that does something other than stupid Matlab tricks.)
A = [ 11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36
41 42 43 44 45 46
51 52 53 54 55 56
61 62 63 64 65 66];
Then
>> A(p,p)
ans =
22 23 24 25 26 21
32 33 34 35 36 31
42 43 44 45 46 41
52 53 54 55 56 51
62 63 64 65 66 61
12 13 14 15 16 11
>>
x([i,j]) = x([j,i])
B =
-0.4326
-1.6656
0.1253
0.2877
-1.1465
1.1909
1.1892
-0.0376
0.3273
0.1746
-0.1867
0.7258
and want to replace all the negative values with zeros.
That is a one-liner in Matlab:
>> B = B - (B<0).*B
B =
0
0
0.1253
0.2877
0
1.1909
1.1892
0
0.3273
0.1746
0
0.7258
This is worth dissecting. The relational operation
B<0 returns a 0-1 array, with 1's where the test is true
and 0 where the test is false:
>> B<0
ans =
1
1
0
0
1
0
0
1
0
0
1
0
We multiply that componentwise times B, to get an array
with just the negative values of B:
>> ans.*B
ans =
-0.4326
-1.6656
0
0
-1.1465
0
0
-0.0376
0
0
-0.1867
0
Subtracting that from B itself cancels out the negative entries.
A final warning for those who know Fortran9x:
the array notation is like Fortran90, but BEWARE:
Matlab's colon notation has