How do I increment a 4-digit number in a character array?

조회 수: 2 (최근 30일)
Brad
Brad 2017년 2월 22일
답변: Walter Roberson 2017년 2월 23일
I've got a 1x4 character array containing a 4-digit number.
IRN = '0050';
I'm looking for a way to increment this number in a for loop. For example, with 3 iterations the output of the for loop would be as follows;
MRN =
0051
0052
0053
Can MATLAB increment numbers, within a character array, in a for loop?

채택된 답변

Star Strider
Star Strider 2017년 2월 22일
I’m not quite sure what you want.
One approach:
IRN = '0050';
IRN0 = IRN;
for k1 = 1:3
IRN = sprintf('%04d', str2num(IRN0)+k1)
end
  댓글 수: 2
Stephen23
Stephen23 2017년 2월 22일
편집: Stephen23 2017년 2월 22일
str2double would be faster and more robust then str2num. sscanf would be best:
IRN = '0098'
for k = 1:5
IRN = sprintf('%04d',1+sscanf(IRN,'%d'))
end
Star Strider
Star Strider 2017년 2월 22일
Good points!

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 2월 23일
IRN = '0098';
L = length(IRN);
for k = 1 : 5
for J = L : -1 : 1;
if IRN(J) == '9'
IRN(J) = '0';
else
IRN(J) = IRN(J)+1;
break;
end
end
disp(IRN)
end

카테고리

Help CenterFile Exchange에서 Networks에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by