冒号操作符

冒号操作符

冒号," : ",是很多重要的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值