简体   繁体   English

MATLAB-仅字符串的第一个字母正在打印

[英]MATLAB - Only First Letter of String is Printing

I am having an issue printing a string in MATLAB (2012a) using the fprtinf command (and sprintf ). 我在使用fprtinf命令(和sprintf )在MATLAB(2012a)中打印字符串时遇到问题。

I have an array of 12 dates (numeric). 我有12个日期(数字)的数组。 I am converting them to strings using the following command: 我正在使用以下命令将它们转换为字符串:

months = datestr(data(:,1)-365,12); %Mar13 format

I obtain the following (and desired) output when I call the months variable: 当我调用months变量时,我得到以下(和期望的)输出:

Jan12 Jan12
Feb12 Feb12
Mar12 Mar12
Apr12 Apr12
etc.. 等等..

The issue is when I call the fprintf or sprintf , say with the following code: 问题是当我调用fprintfsprintf ,用以下代码说:

fprintf('%s', months(1))

I will only get the first letter of the month and not the full string. 我只会得到该月的第一个字母,而不是完整的字符串。 Any idea how to make it print the full string? 任何想法如何使它打印完整的字符串?

Thanks! 谢谢!

The resulting data type for your months variable is an NxM character array. months变量的结果数据类型是NxM字符数组。 You need to process it as a cell array of strings instead. 您需要将其处理为字符串的单元格数组。

dates = num2cell(data(:,1)-365)
months = cellfun(@(x) datestr(x,12),dates,'UniformOutput',false)
fprintf('%s', months{1})

should get you what you want. 应该会给你你想要的。

Simply change your call to 只需将您的电话更改为

fprintf('%s', months(1, :))

datestr returns the string of each of the supplied dates on a separate row. datestr在单独的行上返回每个提供的日期的字符串。

Alternatively you could use the cellstr function to convert the result to a cell array (this would also work with non fixed-length date formats like 'dddd' ) 或者,您可以使用cellstr函数将结果转换为单元格数组(这也可以用于非固定长度的日期格式,例如'dddd'

months = cellstr(months);
fprintf('%s', months{1});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM