How do you add a 0 in front of single digit numbers in a numerical array?

조회 수: 18 (최근 30일)
Marissa Holden
Marissa Holden 2017년 10월 10일
댓글: Rik 2017년 10월 11일
I later want to convert 2 numerical arrays into a string array and then back to a numerical array to combine a series of numbers. HOWEVER - to do this the numbers need to have the same amount of integers otherwise I get an empty matrix.
So my question is, how would I tell matlab to put a 0 in front a singular numbers in a 1x56 numerical array so all the numbers have the same amount of digits?
  댓글 수: 6
Marissa Holden
Marissa Holden 2017년 10월 11일
Could I make another string variable that put a 0 in front of the single digits and then put that into a numerical array?
per isakson
per isakson 2017년 10월 11일
There is no such thing as leading zeros when it comes to numerical variables. Leading zeros in the string variable will vanish when "put that into a numerical".
Try to formulate your question/problem in other words.

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

답변 (1개)

Rik
Rik 2017년 10월 10일
num2str, fprintf and sprintf all have options to specify a format when converting a numeric value to a string.
a=num2cell(1:10);
b=cellfun(@(x) sprintf('%02d',x),a,'UniformOutput',false);
  댓글 수: 2
Jan
Jan 2017년 10월 11일
Or the undocumented:
b = sprintfc('%02d', a);
Rik
Rik 2017년 10월 11일
Cool, that's even 20 times faster. Not strange, as you remove a lot of overhead.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by