How to extract digits
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
Hello everybody. I would like to know how to extract the first digit of each element of a vector.
Example
a = [438;259;21;4;79876]
out = [4;2;2;4;7]
At the same time I would like to know if there is a way to extract the first two digits of each element:
a = [438;259;21;44;79876]
out = [43;25;21;44;79]
tnxxx
채택된 답변
Voss
2022년 3월 23일
1 개 추천
Assuming they're all positive numbers, you can try this (the 2-digit result won't be accurate for one-digit numbers):
a = [438;259;21;44;79876];
power10 = 10.^floor(log10(a));
first_digit = floor(a./power10)
first_digit = 5×1
4
2
2
4
7
first_two_digits = floor(a./power10*10)
first_two_digits = 5×1
43
25
21
44
79
댓글 수: 6
LC
2022년 3월 24일
편집: Image Analyst
2022년 3월 24일
Hi, very thanks for your help! I also wanted to ask you another question: if instead of a vector with numbers I had some text strings, how could I extract the first element?
Ex
a=['ab';'cde','hhh','kbj']
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Dimensions of arrays being concatenated are not consistent.
out=['a';'c';'h';'k']
tnxxxx
Image Analyst
2022년 3월 24일
LC, that syntax is not right. What do you really have? A vector of strings (newer and less common)? Or a cell array of character arrays (older and more common)? They are different.
LC
2022년 3월 25일
Hi, sorry if I've been unclear, I'm just starting out with matlab. I believe it is an array of characters. Now I'm sending you a photo of my variable so maybe it's clearer. Thanks.

Voss
2022년 3월 25일
That is indeed an array of characters (in particular, it is a character vector - a vector being a 1-dimensional array; in this case it is a row vector, i.e., of size 1-by-something).
Here's how you could extract the first digit (or first two digits) of each number in there, resulting in a cell array of character vectors or a character array.
(The idea is to read the character vector ST using sscanf() to get numbers and then use the approach in my answer to get the numeric digit(s), then 'print' those digit(s) to into a cell array or character array using sprintfc() or sprintf().)
ST = '51 51 50 49 49';
a = abs(sscanf(ST,'%f'))
a = 5×1
51
51
50
49
49
power10 = 10.^floor(log10(a));
first_digit = sprintfc('%d',floor(a./power10))
first_digit = 5×1 cell array
{'5'}
{'5'}
{'5'}
{'4'}
{'4'}
first_two_digits = sprintfc('%d',floor(a./power10*10))
first_two_digits = 5×1 cell array
{'51'}
{'51'}
{'50'}
{'49'}
{'49'}
Those are the cell array results, and here's the character array version (with one or two columns depending on if you're taking one or two digits):
first_digit = sprintf('%d',floor(a./power10)).'
first_digit = 5×1 char array
'5'
'5'
'5'
'4'
'4'
first_two_digits = reshape(sprintf('%d',floor(a./power10*10)),2,[]).'
first_two_digits = 5×2 char array
'51'
'51'
'50'
'49'
'49'
Now, let's say ST was like this instead:
ST = '-5.1 +5.1e+002 50.0 -49e-3 49';
Then the approach above will still work:
a = abs(sscanf(ST,'%f'))
a = 5×1
5.1000
510.0000
50.0000
0.0490
49.0000
power10 = 10.^floor(log10(a));
first_digit = sprintfc('%d',floor(a./power10))
first_digit = 5×1 cell array
{'5'}
{'5'}
{'5'}
{'4'}
{'4'}
first_two_digits = sprintfc('%d',floor(a./power10*10))
first_two_digits = 5×1 cell array
{'51'}
{'51'}
{'50'}
{'49'}
{'49'}
first_digit = sprintf('%d',floor(a./power10)).'
first_digit = 5×1 char array
'5'
'5'
'5'
'4'
'4'
first_two_digits = reshape(sprintf('%d',floor(a./power10*10)),2,[]).'
first_two_digits = 5×2 char array
'51'
'51'
'50'
'49'
'49'
But let me reiterate that this approach still has the limitation that the two-digit result for a one-digit number will not be accurate ('4' will return '40' for instance).
In general, the best choice of method will depend on:
- what format(s) the numbers in the ST character vector might possibly be in, and
- what class of variable you want to end up with, e.g., cell array of character vectors, character array, string array, numeric array
ST = '51 51 50 49 49';
DD = regexp(ST,'\d\d','match')
DD = 1×5 cell array
{'51'} {'51'} {'50'} {'49'} {'49'}
LC
2022년 3월 26일
thank you very much for your support, it works great because I never have a one-digit number.
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
참고 항목
웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
