Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: int32(2)/int32(3) gives 1. How to get normal integer division?

Tags:

matlab

When I'm porting code from a language such as C++, Java, Python into Matlab, and need it to behave in the same way with integers.

int32(n) doesn't work with division (see title of post). Is there a type that does?

Edit: Guess what, it turns out that my favourite languages are not as consistent as I thought. C++:

#include <cstdio>
int main() {
    #define TEST(a, b)  printf("%d / %d = %d\n", (a), (b), (a)/(b));
    TEST(-4, 3);
    TEST(4, -3);
    TEST(-5, 3);
    TEST(5, -3);
    TEST(-1, 2);
    TEST(1, -2);
    return 0;
}

Produces:

-4 / 3 = -1
4 / -3 = -1
-5 / 3 = -1
5 / -3 = -1
-1 / 2 = 0
1 / -2 = 0

Python:

def TEST(a, b): return (a)/(b)

>>> TEST(-4, 3);
-2
>>> TEST(4, -3);
-2
>>> TEST(-5, 3);
-2
>>> TEST(5, -3);
-2
>>> TEST(-1, 2);
-1
>>> TEST(1, -2);
-1
like image 884
Evgeni Sergeev Avatar asked Nov 15 '25 16:11

Evgeni Sergeev


1 Answers

By "normal integer division", I take it you mean "floor division", like what the other languages do?

In that case, use idivide with an explicit rounding option:

> idivide(int32(2), int32(3), 'floor')
ans = 0
like image 91
nneonneo Avatar answered Nov 18 '25 19:11

nneonneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!