11 Nov 2022

Generalised Conversion from Any Data Type to String in Matlab

收藏到CSDN网摘

For logging and debugging purpose in Matlab, some parameter values need to be written either to the command window or an external file. To display in the command window, we have two options - disp() and fprintf(). The disp() is very convenient and works with all data types. However, we must stick to fprintf() if more flexible formats are required, such as %f, %g, %s, %d, etc. But it means treating different data types differently. 

Is there a simple and generalised way of doing this? Or is Matlab clever enough to convert any data type to a proper string format for displaying? The answer is YES! By calling the following lambda function 'toString', any date type would be converted to a string that can be displayed by a single function call to 'fprintf('%s', toString(x)'.
% string representation of matlab variable value
toString = @(x) mlreportgen.utils.toString(x);
Examples of using this function are shown below. As we can see, all the variable values are converted to string representations.
>> a = 1; b = 20.0; c = 1e-4; d = [2,3]; e.sub1 = 4; e.sub2 = [232]; f = {'1',2};
>> toString(a)

ans = 

    "1"

>> toString(b)

ans = 

    "20"

>> toString(c)

ans = 

    "1.0000e-04"

>> toString(d)

ans = 

    "[2 3]"

>> toString(e)

ans = 

    "    sub1: 4
         sub2: 232"

>> toString(f)

ans = 

    "{1, 2}"

No comments :

Post a Comment