New to MATLAB, question about num2str
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
Steven Lord
2019-4-11
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.)
0 个评论
Star Strider
2019-4-11
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!