How do I include zeros when converting from an integer to a string?

14 次查看(过去 30 天)
I have a script which reads information from an XML file and converts that information into strings for later use. Here is the part I'm interested in.
function patientID = getPatientID(td)
% getPatientID(td)
%
% patientID = getPatientID(td)
%
% Extracts the patient id for a tSeries-obj. Can accept arrays of
% tSeries objects or single tSeries
%
%INPUTS:
% td - a tSeries object containing the timeseries data to be analyzed.
%
%OUTPUTS:
% patientID - the patient ID for a tSeries-obj : string
%
% BATeplitzky July 1, 2014
% size input array of tSeries objects
sz = builtin('size',td); % size of td
patientID = cell(sz);
td_vec = td(:); % matix to vector
nDFN = length(td_vec); % number of tSeries-objs
% get PatientID of each object
patientID_vec = cell(nDFN,1); % preallocate
for iDFN = 1:nDFN % for each file
try
patientID_vec{iDFN} = td_vec(iDFN).DataInfo.UserData.RecordingItem.PatientID;
catch
patientID_vec{iDFN} = 'NoData';
end
end
% output to match input array of tSeries objects
patientID(:) = patientID_vec;
% make sure the patient ID is a string
patientID = cellfun(@num2str,patientID,'UniformOutput',0);
The code works fine except when the XML file has a number such as "001234", the main program (not shown here for security reasons) reads it as "1234".

采纳的回答

the cyclist
the cyclist 2015-6-26
编辑:the cyclist 2015-6-26
Replace your last line with this:
patientID = cellfun(@(x)sprintf('%06d',x),patientID,'UniformOutput',0)

更多回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2015-6-26
a=1234
b=sprintf('00%d',a)

Star Strider
Star Strider 2015-6-26
Another possibility:
x = 1234;
Q = sprintf('%06d', x)
Q =
001234
It doesn’t add zeros, but does lead-zero-padding out to 6 places in this format. If there are six digits in ‘x’, there are no leading zeros.

产品

Community Treasure Hunt

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

Start Hunting!

Translated by