Evgeni Sergeev
Evgeni Sergeev

Reputation: 23601

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

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

Upvotes: 4

Views: 3638

Answers (1)

nneonneo
nneonneo

Reputation: 179552

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

Upvotes: 12

Related Questions