【问题标题】:Typecast to an int in Octave/Matlab在 Octave/Matlab 中类型转换为 int
【发布时间】:2011-02-03 03:35:44
【问题描述】:

我需要调用使用 linspace 命令创建的矩阵的索引,并基于从示波器获取的一些数据。因此,输入的数据是双精度数。但是,我真的不能打电话:

Time[V0Found]

其中 V0Found 类似于 5.2 但是,采用索引 5 已经足够接近,所以我需要去掉小数点。我用这个等式去掉了小数:

V0FoundDec = V0Found - mod(V0Found,1)
Time[V0FoundDec]

但是,即使这会去掉小数点,八度仍然会抱怨它。

那么,我该怎么做才能将其类型转换为 int?

【问题讨论】:

    标签: arrays matlab indexing octave casting


    【解决方案1】:

    在 MATLAB 中,它应该是 int8(x)int16(x)one of the other integer casts

    但我很惊讶您需要为索引执行此操作。试试

    myarray(floor(indexlist))
    

    myarray(round(indexlist))
    

    myarray 是您的数组,indexlist 是您的非整数索引向量。


    示例:

    octave-3.2.3:8> v=rand(1,8)*10+1
    v =
    
       3.1769   1.4397   8.7504   1.7424   6.9413   3.1663   8.4085   9.0179
    
    octave-3.2.3:9> a = (1:1:20).^2
    a =
    
     Columns 1 through 15:
    
         1     4     9    16    25    36    49    64    81   100   121   144   169   196   225
    
     Columns 16 through 20:
    
       256   289   324   361   400
    
    octave-3.2.3:10> a(floor(v))
    ans =
    
        9    1   64    1   36    9   64   81
    

    【讨论】:

    • 你的想法确实有效,虽然它在脚本中不起作用,但我猜我一定只是对 X 有一个非常小的值。
    【解决方案2】:

    您可以使用 roundfloorceil 函数代替公式来进行舍入。

    顺便说一句,索引是使用括号而不是括号来完成的:

    V0FoundDec = round(V0Found);
    Time(V0FoundDec) % not Time[V0FoundDec]
    

    如果这是你的问题

    【讨论】:

      【解决方案3】:

      在matlab中,正确的做法是使用interp1命令进行插值。该命令的格式为

      yout = interp1 (xdata, ydata, xin, ...) 要么 yout = interp1 (ydata, xin, ...) 然后假设 xdata 为 1:length(ydata)

      如果你想产生你会从调用中得到的结果

      V0FoundDec = Time(round(V0found))

      你会说

      V0FoundDec = interp1(Time, V0found, 'nearest')

      但是您可以使用

      轻松获得线性插值(这是默认设置)

      V0FoundDec = interp1(时间, V0found)

      V0FoundDec = interp1(Time,V0found,'linear')

      您还可以在限制之外推断(使用“extrap”或提供额外值),其中

      时间(回合(V0found))

      如果 round(V0found) length(Time) 会崩溃

      【讨论】:

        猜你喜欢
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        • 2020-10-10
        • 2016-07-01
        • 2017-04-30
        • 2014-02-20
        • 2016-03-12
        • 2017-11-05
        相关资源
        最近更新 更多