How can MATLAB's buit-in function give output as class single intead of double?
Show older comments
All matlab function gives output as class double.
e.g.
[I,J] = ind2sub([H W],idx);
it is clear that I & J will be integer type but then also matlab gives values of I & J as class double.
How can get output as class interger 'int16'?
5 Comments
Matt J
on 25 Aug 2018
Why not just post-convert I and J?
I=int16(I);
J=int16(J);
JAI PRAKASH
on 25 Aug 2018
One reason it is possible with zeros() is because zeros() doesn't do any calculations.
ind2sub cannot work well if it does calculations purely in integer type. Suppose you had a 1000x1000 matrix. All the (I,J) coordinates are representable as int16, but the range of idx values is not covered by int16. Therefore idx, and any calculations involving idx, must first be done in floating point.
Walter Roberson
on 26 Aug 2018
Well, they could be done as uint64.
It would not be unreasonable for MATLAB to support passing in the name of the output type for ind2sub, but it does not currently do so.
JAI PRAKASH
on 26 Aug 2018
Edited: JAI PRAKASH
on 26 Aug 2018
Answers (1)
Matt J
on 25 Aug 2018
function [I,J]=myind2sub(sz,idx)
I= mod(idx,int16(sz(1)));
J= int16( ceil(idx/sz(2)) );
end
7 Comments
JAI PRAKASH
on 25 Aug 2018
No, there is no general approach. In addition to my comment above, the reason you can do things like zeros(...,'int16') is because a separate version of zeros() exists for every data type. Because zeros() is written in C/C++, the different versions were probably auto-generated easily enough using template functions. Regardless, the ability of any function to generate output directly of different types is, at some level, achieved by providing multiple, alternative implementations of the same function.
JAI PRAKASH
on 25 Aug 2018
Matt J
on 25 Aug 2018
With ind2sub, you must post-convert the results from floating point to integer. That's the only way it will work well.
JAI PRAKASH
on 25 Aug 2018
Edited: JAI PRAKASH
on 25 Aug 2018
Stephen23
on 25 Aug 2018
@JAI PRAKASH: then copy ind2sub to your working directories, rename it myind2sub, and make whatever changes you want to the code. Do NOT change the original file.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!