extracting numbers from a string in an array
21 views (last 30 days)
Show older comments
Hi,
I have an array, p, approximately 1200 rows long, and inside each cell in the array is a string with a number inside it, for example:
p(3,1)=
'"rainfall":0.1'
For each cell in the array I am trying to extract the number value. So for the above case I want the cell to simply have the number 0.1
Any ideas on how to do this? The length of the strings in each cell will be the same length, and have exactly the same characters - the only thing that changes is the number.
Many Thanks,
Sam
0 Comments
Accepted Answer
Andrei Bobrov
on 20 Sep 2012
out = cellfun(@(x)str2double(regexp(x,'\d*\.\d*','match')),p);
0 Comments
More Answers (1)
Jan
on 20 Sep 2012
Edited: Jan
on 20 Sep 2012
I assume this is faster than the regexp approach:
p = {'"rainfall":0.1', '"rainfall":0.2', '"rainfall":0.333'};
s = sprintf('%s*', p{:});
numbers = sscanf(s, '"rainfall":%g*');
Alternative, which could be faster also:
q = strrep(p, '"rainfall":', '');
s = sprintf('%s*', p{:});
numbers = sscanf(s, '%g*');
To avoid a hardcoding of the string '"rainfall":':
index = strfind(p{1}, ':');
key = p{1}(1:index(end));
q = strrep(p, key, '');
5 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!