How can MATLAB's buit-in function give output as class single intead of double?

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

Why not just post-convert I and J?
I=int16(I);
J=int16(J);
because it is another process.
I am looking for something similar to how we can create zeros directly of a particular class. e.g. zeros(5, 'uint16')
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.
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.
Thanx @ Walter. for commenting.
I agree with you regarding uint64

Sign in to comment.

Answers (1)

function [I,J]=myind2sub(sz,idx)
I= mod(idx,int16(sz(1)));
J= int16( ceil(idx/sz(2)) );
end

7 Comments

My concern is not particluar towards a single function. But thanks
I am seeking for general approach for any function.
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.
Ok, I understood.
I think, I can edit ind2sub and there I can use default int16 elements.
With ind2sub, you must post-convert the results from floating point to integer. That's the only way it will work well.
What I am saying is, if inside ind2sub function 'double' is replaced with 'int16'.
I can get the desired result at no extra cost. Because in my case, nout=2.
@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.
Yes, if you change the built-in ind2sub, you jeopardize the functionality of other Matlab built-ins that rely on its normal behavior.

Sign in to comment.

Products

Release

R2018a

Tags

Asked:

on 25 Aug 2018

Edited:

on 26 Aug 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!