user2952272
user2952272

Reputation: 341

Square root of type int32 variable

I tried to calculate the square root of a type int32 variable using the sqrt() function, but I got this error: Undefined function 'sqrt' for input arguments of type 'int32'. Then I found that there's a function called isqrt() that calculates the square root of type integer variables but it doesn't exist in my Matlab version (R2013a). I tried to download this function but I can't find it. I tried powering the value to (1/2) but integers can only be raised to positive integral powers.

So is there any way to do this?

Upvotes: 2

Views: 2545

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

Here is a solution that avoids rounding that happens when you convert from double to an integer type by using fix and also it supports any integer type by using cast and class functions:

isqrt = @(x) cast(fix(sqrt(double(x))), class(x));

So for example:

>> isqrt(int32(15))
ans =
    3

However

>> int32(sqrt(double(int32(15))))
ans =
           4

Use fix instead of floor to handle negative values correctly:

>> isqrt(int8(-15))
ans =
    0 +    3i

Upvotes: 1

Robert Seifert
Robert Seifert

Reputation: 25232

You could write your own isqrt using an anonymous function:

%// variable
A = int32(16)

%// helper function
isqrt = @(x) int32(sqrt(double(x)))

%// root
iroot = isqrt(A)

This function should just used as that, if you're sure that it actually possible to calculate the root, as casting a decimal value to int32(...) will round it, without displaying an error.

So to make it a little more robust, you could create a function like:

function iroot = isqrt(integer)

    root = sqrt(double(integer));
    if mod(root,1) == 0
        iroot = int32( root );
    else
        disp('Input has no integer root')
    end

end

Upvotes: 3

Related Questions