如何将函数强制为 return int32 整数?

How to force function to return int32 integers?

我在 Matlab 中有一个我定义的命令,它应该 return 整数值:

x = intlinprog(f,intcon,A,b,Aeq,beq,lb,ub)

我不想对结果进行四舍五入。我希望值从一开始就是 int

这是我试过的:

x = int32([0 0 0 0 0 0 0  ])   
x = intlinprog(f,intcon,A,b,Aeq,beq,lb,ub)

%// but this is not working, and not giving integer values.

知道如何强制 x 成为 int 值而不是 double 的矩阵吗?

您可以将双精度四舍五入为整数

x = round(intlinprog(f,intcon,A,b,Aeq,beq,lb,ub))

定义在

中的x
x = int32([0 0 0 0 0 0 0]) 

覆盖
x = intlinprog(f,intcon,A,b,Aeq,beq,lb,ub)

所以你有三个选择:

1) 在您的函数外强制转换 int32

x = int32(intlinprog(f,intcon,A,b,Aeq,beq,lb,ub))

2) 或内部

function [ output ] = intlinprog(...)
   ...
   ...

   output = int32( output )

end

使用round before, if you think it is necessary. Consider also ceil, floor and fix.

3) 或者最后,可能是您真正想要的,正确使用预先分配的数组:

x = int32( [0 0 0 0 0 0 0] )  
x(1:end) = int32(intlinprog(f,intcon,A,b,Aeq,beq,lb,ub))

by x(1:end) 不是 覆盖先前定义的 x,而是填充其数组元素并因此保持数据类型。不过,函数的输出和预分配的数组需要具有相同的大小。

Matlab 倾向于在执行计算之前将整数转换为双精度数,您几乎无能为力,同时避免任何形式的过度复杂性。您必须修改您的函数,以便在执行所有计算后将结果类型转换回 int32。我从未检查过这个事实,但由于 Matlab 基本上是 Java 的包装器,我担心它可能会以同样的方式工作:当浮点值被转换为整数值时,它们基本上被截断了。因此:

Float      Integer
10.87  ->  10
10.14  ->  10

这就是为什么我建议您在使用 int32 function 转换值之前对值进行舍入以避免失去太多精度:

function result = intlinprog(...)
    % Your computations here...
    result = int32(round(result));
end

编辑

我检查过:

A = [
   10.53;
   10.01;
   10.44;
   10.87
];

int32(A)

ans =

  4×1 int32 column vector

   11
   10
   10
   11

结果让我假设在类型转换之前在内部执行了舍入到最接近的整数。所以你可以使用:

function result = intlinprog(...)
    % Your computations here...
    result = int32(result);
end

没有问题。

这是来自 documentationintcon 的示例 :

Example: intcon = [1,2,7] means x(1), x(2), and x(7) take only integer values.

因此,如果您希望 x 的所有元素都是整数,您应该将 intcon 设置为 1:numel(f)