MATLAB中冒号运算符的含义 [英] The meaning of colon operator in MATLAB

查看:140
本文介绍了MATLAB中冒号运算符的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些我不完全理解的MATLAB语法.

I came across some MATLAB syntax with a colon that I don't fully understand.

表达式:0:pi/4:pi 结果为:0 0.7854 1.5708 2.3562 3.1416

为什么会这样?我认为将冒号运算符用作引用索引的快速方法,这样我们就不必写出完整的列表. (例如1:3-> 1 2 3)

Why is this the case? I thought that colon operator is used as a quick way to refer to indices so that we don't have to write out the full list. (e.g. 1:3 -> 1 2 3)

与上述类似,假设我有矩阵X = [1 2 3 4 5 6 7 8 9].如何解释表达式X(:,1:3)?具体来说,没有左右数字的冒号运算符是什么意思?

Similar to above, say if I have a matrix X = [1 2 3 4 5 6 7 8 9]. How can I interpret the expression X(:,1:3)? Specifically, what does the colon operator without the left and right numbers mean?

推荐答案

实际上a:b会生成一个向量.您只能将其用作索引,因为(...)也会接受列表,例如

Actually a:b generates a vector. You could use it as index only because the (...) accepts a list also, e.g.

octave-3.0.3:10> a = [1,4,7]
a =

   1   4   7

octave-3.0.3:11> b = [1,4,9,16,25,36,49]
b =

    1    4    9   16   25   36   49

octave-3.0.3:12> b(a)    # gets [b(1), b(4), b(7)]
ans =

    1   16   49

现在,a:b:c语法等效于[a, a+b, a+2*b, ...],直到c,例如

Now, the a:b:c syntax is equivalent to [a, a+b, a+2*b, ...] until c, e.g.

octave-3.0.3:15> 4:7:50
ans =

   4  11  18  25  32  39  46

解释了您在0:pi/4:pi中得到的东西.

which explains what you get in 0:pi/4:pi.

一个孤独的:选择整个轴(行/列),例如

A lone : selects the whole axes (row/column), e.g.

octave-3.0.3:16> a = [1,2,3;4,5,6;7,8,9]
a =

   1   2   3
   4   5   6
   7   8   9

octave-3.0.3:17> a(:,1)   # means a(1:3, 1)
ans =

   1
   4
   7

octave-3.0.3:18> a(1,:)   # means a(1, 1:3)
ans =

   1   2   3


有关详细信息,请参见冒号(:) 上的官方MATLAB文档.


See the official MATLAB doc on colon (:) for detail.

这篇关于MATLAB中冒号运算符的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆