# How to get the last two digits of a number?

132 ビュー (過去 30 日間)
Maximilian Lingel 2021 年 5 月 10 日
コメント済み: Adam Danz 2021 年 5 月 10 日
Hello,
I have a table with 505 rows and 1 column. Each row contains a 4 digit number and from of these numbers I would like to extract the last two digits to add a second column to that table containing the last two digits of every number in the first column.
I would be grateful for any hints. Thank you

サインインしてコメントする。

### 採用された回答

David Fletcher 2021 年 5 月 10 日
x=4974
y=floor((x/100-floor(x/100))*100)
##### 1 件のコメント表示非表示 なし
Adam Danz 2021 年 5 月 10 日
+1 faster than mod
Comparison of the two methods
1000
rng(123)
x = round(rand(5000,1)*10000);
n = 10000;
t1 = tic;
cumulativeTime1 = nan(n,1);
for i = 1:n
v = floor((x/100-floor(x/100))*100);
cumulativeTime1(i) = toc(t1);
end
pause(1)
t2 = tic;
cumulativeTime2 = nan(n,1);
for i = 1:n
w = mod(x,100);
cumulativeTime2(i) = toc(t2);
end
duration1 = diff(cumulativeTime1);
duration2 = diff(cumulativeTime2);
figure
hold on
plot(duration1,'DisplayName','floor')
plot(duration2,'DisplayName','mod')
xlabel('Iteration')
ylabel('time (sec)')
legend() サインインしてコメントする。

### その他の回答 (1 件)

DGM 2021 年 5 月 10 日
Assuming they're integers:
% 10 rows random integers
n = (randi(8999,1,10)+1000)'
n = [n mod(n,100)]
If they aren't integers, you should decide how you want to round them first.
##### 3 件のコメント表示非表示 2 件の古いコメント
Adam Danz 2021 年 5 月 10 日
Either of the two existing solutions will work with 4-digit integers but note that if the 3rd digit is a 0 as in 4206, the extraction will be 6 and not 06 since matlab does not preserve the 0 place holder. If you want to retain the 0, you'll need to extract the digis as strings or character vectors.
Method 1: convert to string after extraction
rng(123) % for reprodicibility
x = round(rand(10,1)*10000);
lastTwo = mod(x,100);
charVec = compose('%02d',lastTwo); % for char-vectors
str = string(compose('%02d',mod(x,100))); % for string array
T = table(x, lastTwo, charVec, str)
T = 10×4 table
x lastTwo charVec str ____ _______ _______ ____ 6965 65 {'65'} "65" 2861 61 {'61'} "61" 2269 69 {'69'} "69" 5513 13 {'13'} "13" 7195 95 {'95'} "95" 4231 31 {'31'} "31" 9808 8 {'08'} "08" 6848 48 {'48'} "48" 4809 9 {'09'} "09" 3921 21 {'21'} "21"
Method 2: convert to string and then extract
rng(123) % for reprodicibility
x = round(rand(10,1)*10000);
xstr = string(x);
str = extractAfter(xstr,2);
T = table(x, lastTwo, str)
T = 10×3 table
x lastTwo str ____ _______ ____ 6965 65 "65" 2861 61 "61" 2269 69 "69" 5513 13 "13" 7195 95 "95" 4231 31 "31" 9808 8 "08" 6848 48 "48" 4809 9 "09" 3921 21 "21"

サインインしてコメントする。

### Community Treasure Hunt

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

Start Hunting!