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

7 vues (au cours des 30 derniers jours)
DeeWBee
DeeWBee le 26 Juin 2015
Commenté : Azzi Abdelmalek le 26 Juin 2015
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".

Réponse acceptée

the cyclist
the cyclist le 26 Juin 2015
Modifié(e) : the cyclist le 26 Juin 2015
Replace your last line with this:
patientID = cellfun(@(x)sprintf('%06d',x),patientID,'UniformOutput',0)

Plus de réponses (2)

Azzi Abdelmalek
Azzi Abdelmalek le 26 Juin 2015
a=1234
b=sprintf('00%d',a)
  1 commentaire
Azzi Abdelmalek
Azzi Abdelmalek le 26 Juin 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)

Connectez-vous pour commenter.


Star Strider
Star Strider le 26 Juin 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.
  2 commentaires
DeeWBee
DeeWBee le 26 Juin 2015
Ah okay! I understand now. Thanks!
Star Strider
Star Strider le 26 Juin 2015
My pleasure!

Connectez-vous pour commenter.

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by