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!

Get DateTime as a Formatted String in Matlab

收藏到CSDN网摘

A very common task would be obtain the current timestamp while writing code in any programming languages, especially for logging and debugging purpose. Almost all the languages provide support for retrieving the current date and time using either built-in or 3rd party libs. 

Matlab has some built-in formats already. All we need to do is to pass the proper format number to its 'datestr()' function. To obtain the current time and date, 'now' can be passed to the 'datestr()' function as the first parameter. The 2nd parameter is for specifying the format. Someone may write code like "datestr(now, 'yyyy-mm-dd HH:MM:SS')" to get a timestamp such as 2022-11-10 00:00:42. However, apart from explicitely writing out the format string, Matlab also supports specifying the format using a single number - "datestr(now, 31)" will give you the same result. How about other formats?