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.
  2 件のコメント
DeeWBee
DeeWBee 2015 年 6 月 26 日
Ah okay! I understand now. Thanks!
Star Strider
Star Strider 2015 年 6 月 26 日
My pleasure!

サインインしてコメントする。

製品

Community Treasure Hunt

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

Start Hunting!

Translated by