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

조회 수: 7 (최근 30일)
DeeWBee
DeeWBee 2015년 6월 26일
댓글: Azzi Abdelmalek 2015년 6월 26일
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)
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2015년 6월 26일
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)

댓글을 달려면 로그인하십시오.


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