I am trying to create function that accepts an input array, A, and converts it to the smallest integer class for which it can be stored without changing the information in the matrix. If the matrix does not have any negative numbers it needs to be converted to the smallest possible unsigned integer type. Lastly, if none of the integer types are suitable, the matrix is returned without changing.
I am super new to MATLAB, so I hardly know all the built-in functions to make this code easy, nor do I really understand how MATLAB stores the information, but I have attached my code attempt below.
function smallint = store_small(A)
A = ;
[rows, cols] = size(A);
for ii = 1:rows
for jj = 1:cols
if any(A(ii, jj)) < 0
if A(ii, jj) >= (-2)^7 && A(ii, jj) <= (2^7)-1
smallint = int8(A);
elseif A(ii, jj) >= (-2)^15 && A(ii, jj) <= (2^15)-1
smallint = int16(A);
elseif A(ii, jj) >= (-2)^31 && A(ii, jj) <= (2^31)-1
smallint = int32(A);
elseif A(ii, jj) >= (-2)^53 && A(ii, jj) <= (2^53)-1
smallint = int64(A);
smallint = A;
if A(ii, jj) <= (2^8)-1
smallint = unit8(A);
elseif A(ii, jj) <= (2^16)-1
smallint = unit16(A);
elseif A(ii, jj) <= (2^32)-1
smallint = unit32(A);
elseif A(ii, jj) <= (2^64)-1
smallint = unit64(A);
smallint = A;
As you can tell, I took the time to type out all of those inequalities which is probably a rather monotonous way to do it for the more advanced. Either way, I'm hoping someone can tell me where I'm going wrong.
- my function does not return a matrix. I'm not sure if this is due to the ; or just because the code is not right.
- my function also gives an incorrect output for the input zero.
- i did not add second conditions to each "elseif" statement when dealing with A values that were all greater than zero because I think MATLAB checks the elseif statements one at a time and if it is true, spits out the respective value of that elseif statment and stops. I could be wrong though.
Please help me :) Thanks.