Using a specific number of digits

조회 수: 63 (최근 30일)
John Carroll
John Carroll 2022년 10월 28일
댓글: John Carroll 2022년 10월 31일
I am looking for a way to fix the number of digital in an array. I am attempting to run a for loop in the form "for k = 1:N where n will be an interger typically between 10 and 200. However as it counts through the loop it will report k as 1, 2, 3 etc. I would like to force k to be three digits such as k = [001 002 003.....010 011 012......100 101 102]
Is there a simple way to do this?
Thanks you

채택된 답변

John D'Errico
John D'Errico 2022년 10월 28일
편집: John D'Errico 2022년 10월 28일
Are numbers typically written with leading zero digits? (NO. At least not in anything I've ever done.) The number 001 is no different from the number 1. As such MATLAB returns it as that. No leading digits, at least not if you want it in a numeric form.
Can you force MATLAB to convert an integer so it always return leading zero digits if they would be there? Not as a number. Sorry. But if you want the result to be in a character form, you could do this:
x = 12;
dec2base(x,10,3)
ans = '012'
That will force it to always prepend leading zero digits, so there are always 3 digits shown. HOWEVER, the result is NOT a number. It is just a string of characters at this point..
  댓글 수: 2
John Carroll
John Carroll 2022년 10월 29일
The number is part of a file name and always shows as a three digit number so 1 is 001 and 10 is 010 then a three digit number is just 100 and so on.
Stephen23
Stephen23 2022년 10월 29일
"The number is part of a file name ..."
You should have mentioned this important information in your question. As John D'Errico correctly wrote, numeric types do not store leading zeros, but this is trivial to achieve using SPRINTF et al.

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

추가 답변 (1개)

Jeff Miller
Jeff Miller 2022년 10월 28일
Maybe by "report k" you are referring to printing it, in which case this should work
for k=1:100
fprintf('%03d\n',k)
end
  댓글 수: 4
Stephen23
Stephen23 2022년 10월 29일
Much better without the text concatenation and newline character:
fname = sprintf('MyFile%03d.mat',k);
John Carroll
John Carroll 2022년 10월 31일
This seems to work as well. Thanks.

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

카테고리

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

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by