New to MATLAB, question about num2str

조회 수: 4 (최근 30일)
lachlan
lachlan 2019년 4월 11일
답변: Steven Lord 2019년 4월 11일
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

답변 (2개)

Steven Lord
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.)

Star Strider
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.

카테고리

Help CenterFile Exchange에서 String에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by