Search code examples
matlaboctavematlab-deploymentmatlab-compiler

Automatic Type conversion of row vector in MATLAB


Say I have a row vector defined as follows:

x = [5 6.7 8.9]

The above code results in a row vector with all the elements being typecasted as floating points(including the 5 in the 1st index).

x =

   5.0000   6.7000   8.9000

Is there any way I can prevent the typecasting of the 5 (present in the first place), i.e. is there any way I can get my vector as follows:

x =

   5  6.7000   8.9000

without the four decimal points after the 5.


Solution

  • In Matlab and Octave, double is the default value for all numeric values, even if some of those values might be whole numbers (integers). And for numeric arrays, all elements must be of the same type.

    In general, you should just leave all your numeric values as doubles, and use formatting controls (like those provided by printf() and its friends) to display them how you want.

    In this case, you could do something like:

    x = [5 6.7 8.9];
    printf('%d  %.04f  %.04f\n', x); 
    

    Or to be more flexible:

    printf('%g  ', x); printf('\n');