简体   繁体   中英

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

I have an array of 12 dates (numeric). 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:

Jan12
Feb12
Mar12
Apr12
etc..

The issue is when I call the fprintf or sprintf , say with the following code:

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

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' )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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