冒号操作符

来源:互联网 发布:slice 数组 编辑:程序博客网 时间:2024/04/29 12:37

冒号操作符

冒号," : ",是很多重要的MATLAB操作符之一。它出现在几种不同的格式中。表述

1:10

一个行向量含有整数格式1到10,

1     2     3     4     5     6     7     8     9    10

得到非单元,规定一个增量。例如,

100:-7:50

100    93    86    79    72    65    58    51

然而

0:pi/4:pi

0    0.7854    1.5708    2.3562    3.1416

下标表达式包括冒号并涉及到了矩阵的部分,

A(1:k,j)

首先A的第j列的元素k。因此

sum(A(1:4,4))

计算第四列的和。但是有一个更好的方式。冒号表示在矩阵中一行或列的所有元素,关键词end表示最后行或列。因此

sum(A(:,end))

计算A的最后列的元素的和

ans =
     34

为什么4*4魔方的行或列的和均是34?如果整数从1到16被均分为四组,分别求和,其和必是

sum(1:16)/4

其固然是

ans =
     34

 

The Colon Operator

The colon, :, is one of the most important MATLAB operators. It occurs in several different forms. The expression

1:10

is a row vector containing the integers from 1 to 10,

1     2     3     4     5     6     7     8     9    10

To obtain nonunit spacing, specify an increment. For example,

100:-7:50

is

100    93    86    79    72    65    58    51

and

0:pi/4:pi

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 column. But there is a better way. The colon by itself refers to all the elements in a row 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