Page 107 - Basics of MATLAB and Beyond
P. 107
29.2 Operations with Multidimensional Arrays
Many matrix operators work with multidimensional arrays. For example,
the columnar sum of our 3 × 3 × 2 matrix, a,is
>> a
a(:,:,1) =
1 2 3
4 5 6
7 8 9
a(:,:,2) =
3 3 3
3 3 3
3 3 3
>> sum(a)
ans(:,:,1) =
12 15 18
ans(:,:,2) =
9 9 9
If you look carefully, you will see that the result of the sum is a 1×3×2
matrix:
>> size(sum(a))
ans =
1 3 2
This is not the same as a 3 × 2 matrix. If you want the result to be
a3 × 2 matrix, you can use the squeeze function, which gets rid of
singleton dimensions:
>> squeeze(sum(a))
ans =
12 9
15 9
18 9
matlab does not do an automatic squeeze whenever the result has sin-
gleton dimensions because there are times when you need the singleton
dimension to add more data.
If you want to sum over other dimensions than the rows, you give a
second parameter to the sum function specifying the dimension you want
to sum over. For example, to sum over columns:
>> sum(a,2)
ans(:,:,1) =
6
15
24
c 2000 by CRC Press LLC