Is there a way to extract parts of a multi digit number in MatLab?

88 views (last 30 days)
Title says it all. I'm wondering if there is a way to extract parts of a multi digit number in MatLab?
For example: user enter 1298 I want to take out the first two digits (12) set it equal to some variable, and the last two digits (98) and set that to some variable. I was thinking there might be some way to do this using strings, but I was wondering what you guys thought.

Answers (3)

Walter Roberson
Walter Roberson on 7 Mar 2012
Edited: Stephen23 on 27 Feb 2017
s = num2str(1298);
s12 = str2double(s(1:2));
s34 = str2double(s(3:4));
  5 Comments
Brendan Görres
Brendan Görres on 29 Nov 2021
What would I have to do if I don't have a single scalar but a vector? So that I extract of every number in each row digit 1 and 2 to a variable and 3 and 4 to another.
Image Analyst
Image Analyst on 29 Nov 2021
@Brendan Görres, perhaps you didn't look over all the answers (like mine). Just apply it to your vector:
a = [1298; 3467; 5010]; % Vector with different numbers in each row.
first2 = floor(a/100)
first2 = 3×1
12 34 50
second2 = rem(a, 100)
second2 = 3×1
98 67 10

Sign in to comment.


Image Analyst
Image Analyst on 8 Mar 2012
Not sure why you're interested in using strings, but if that's not a requirement you can do this:
a=1298
first2 = floor(a/100)
second2 = rem(a, 100)
  29 Comments
Anna2017
Anna2017 on 2 Mar 2017
Hi Walter, This works good in the command window, that is why previously I had said it works. its just when I import in the values from the original file somehow from beginning the value gets converted to wrong value: To answer your question, the results are as the following:
S = 1475053846314510000
ans =
[1475053846] [314510000]
Walter Roberson
Walter Roberson on 2 Mar 2017
Not much more I can do without a sample .csv file of at least one line that gives the wrong result for you.

Sign in to comment.


zahid Hasan
zahid Hasan on 22 Jan 2017
Edited: Walter Roberson on 22 Jan 2017
k=double(num2str(1298))-double('0');
% k becomes k=[1 2 9 8]
  2 Comments
Image Analyst
Image Analyst on 22 Jan 2017
He wanted
k1 = 12
k2 = 98
However it's still not clear if he's starting with a number (as my answer assumes), or a string (as Walter's answer assumes). Since it is now 5 years later, I doubt we'll ever get an answer.
Walter Roberson
Walter Roberson on 22 Jan 2017
The user was starting with a number; that's what my answer assumed.

Sign in to comment.

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!