
Matrices and Mag ic Squares
is
0 0.7854 1.5708 2.3562 3.1416
Subscript expressions involving colons refer to portions of a matrix:
A(1:k,j)
is the first k elements of the jth column of A.So
sum(A(1:4,4))
computes the sum of the fourth colum
n. But there is a better way. The colon
by itself refers to all the elements
in a r ow or column of a matrix and the
keyword
end refers to the last row or
column. So
sum(A(:,end))
computes the sum of the elements in the last column of A:
ans =
34
Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1
to 16 are sorted into four groups with equal sums, that sum must be
sum(1:16)/4
which, of course, is
ans =
34
The magic Function
MATLAB actually has a built-in function that creates magic squares of almost
any size. Not surprisingly, this function is named
magic:
B = magic(4)
B=
162313
51110 8
97612
41415 1
2-9
Kommentare zu diesen Handbüchern