How to extract digits

조회 수: 31 (최근 30일)
LC
LC 2022년 3월 23일
댓글: LC 2022년 3월 26일
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
Voss 2022년 3월 23일
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
Stephen23
Stephen23 2022년 3월 25일
ST = '51 51 50 49 49';
DD = regexp(ST,'\d\d','match')
DD = 1×5 cell array
{'51'} {'51'} {'50'} {'49'} {'49'}
LC
LC 2022년 3월 26일
thank you very much for your support, it works great because I never have a one-digit number.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by