New to MATLAB, question about num2str

3 views (last 30 days)
lachlan
lachlan on 11 Apr 2019
Answered: Steven Lord on 11 Apr 2019
Hey, I'm learning MATLAB and I'm trying to include a few lines in my script that will turn clock into a string.
What I've written works fine but it gets the warning "The variable 'datetime' appears to change size on every loop iteration. Consider preallocating for speed." I've copied what I've written below.
clk = clock;
datetime = [];
for clkoutput = 1:(length(clk)-1)
datetime = [datetime num2str(clk(clkoutput))];
end
datetime
datetime =
'20194112221'
I understand that the way to avoid this is to preallocate variables for the length of the array you wish to create, for example by using
datetime = zeros(1, (length(clk)-1)
but when I do this I end up with 5 blank spaces before the date I wish to turn into a string. I know that it doesn't really matter because its a small array but I'm still curious how I could preallocate variables for something I want to then turn into a string and avoid having the 5 blank spaces at the start of the string.
Thanks

Answers (2)

Steven Lord
Steven Lord on 11 Apr 2019
I recommend not using datetime as the name of your variable as it already has a meaning in MATLAB. If you want to use a datetime object to store your date and time data and convert it into text data, use the string function.
A = datetime('today') + days(0:3).'
S = string(A)
tomorrow = S(2) % or string(A(2))
See this section of the documentation for more information about how to work with string arrays (and how to convert them to char vectors if you need to pass them into code that expects char vectors instead of string arrays.)

Star Strider
Star Strider on 11 Apr 2019
Rather than concatenating the ‘clk’ vector into one string that will be difficult to read, consider using the datestr (link) function.
I have no idea what you want to do with the loop.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!