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

6 views (last 30 days)
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".

Accepted Answer

the cyclist
the cyclist on 26 Jun 2015
Edited: the cyclist on 26 Jun 2015
Replace your last line with this:
patientID = cellfun(@(x)sprintf('%06d',x),patientID,'UniformOutput',0)

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 26 Jun 2015
a=1234
b=sprintf('00%d',a)
  1 Comment
Azzi Abdelmalek
Azzi Abdelmalek on 26 Jun 2015
You can save the first 0 in v1 and the result from str2num(a) in v2
a='00126'
b=regexp(a,'[^0]+')
v1=repmat('0',1,b-1)
v2=str2num(a)

Sign in to comment.


Star Strider
Star Strider on 26 Jun 2015
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.

Products

Community Treasure Hunt

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

Start Hunting!