Write a function called integerize that takes as its input a matrix A of integers of type double, and returns the name of the “smallest” signed integer class to which A can be converted without loss of information. If no such class exists, the text '
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
abdelrahman mohamed
il 29 Ott 2018
Commentato: abdelrahman mohamed
il 1 Nov 2018
%for every input the function gives int8 as an output
function x=integerize(A)
[m,n]=size(A);
for ii=1:m
for jj=1:n
if isa(A(ii,jj),'double')
b=min(A);
if -128 <= b <= ((2^7)-1)
x='int8';
elseif (-2^15)<= b <= ((2^15)-1)
x='int16';
elseif (-2^31)<=b<= ((-2^31)-1)
x='int32';
elseif (-2^63)<=b<=((2^63)-1)
x='int64';
else
x='NONE';
end
else
x='NONE';
end
end
end
Risposta accettata
James Tursa
il 29 Ott 2018
Modificato: James Tursa
il 29 Ott 2018
You can't write multiple if conditions this way in MATLAB:
if -128 <= b <= ((2^7)-1)
You have to break it up into individual conditions. E.g.,
if -128 <= b & b <= ((2^7)-1)
Why are you doing the following:
b=min(A);
Hint: The following will turn A into a column vector of all the elements:
b = A(:);
Instead of using for loops, you can then write logic to test all of the elements of b at once to get your result.
Caution: You are going to have a problem with this part of your test for int64:
elseif (-2^63)<=b & b<=((2^63)-1)
The reason is that an int64 actually has more precision than a double, so you can get into trouble comparing numbers near the limits. E.g.,
>> intmax('int64')
ans =
int64
9223372036854775807
>> b = 2^63;
>> num2strexact(b)
ans =
'9.223372036854775808e18'
Just looking at these numbers you can see that b is too large to fit in an int64 class variable. But look what happens with the test that you have:
>> b <= ((2^63)-1)
ans =
logical
1
It returned true! Obviously this is an incorrect result for what you are trying to test. What is the problem? It is the fact that a double precision variable does not have enough precision to do the (2^63)-1 calculation exactly. E.g.,
>> eps(2^63)
ans =
2048
The spacing between numbers near 2^63 in IEEE double is 2048, much larger than the 1 you are trying to do arithmetic with. E.g., look at these results:
>> num2strexact((2^63))
ans =
'9.223372036854775808e18'
>> num2strexact((2^63)-1)
ans =
'9.223372036854775808e18'
>> num2strexact((2^63)-10)
ans =
'9.223372036854775808e18'
>> num2strexact((2^63)-100)
ans =
'9.223372036854775808e18'
You get the same number in each case. Subtracting 1, 10, or 100 had no effect on the answer because they are too far below eps(2^63). So, you will need to rewrite this test. Hint: What would happen if you tried to do this test in int64 arithmetic instead of double arithmetic? Try it out ...
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Testing Frameworks in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!