extracting numbers from a string in an array

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 9월 20일

2 개 추천

out = cellfun(@(x)str2double(regexp(x,'\d*\.\d*','match')),p);

추가 답변 (1개)

Jan
Jan 2012년 9월 20일
편집: Jan 2012년 9월 20일

4 개 추천

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

Sam harris
Sam harris 2012년 9월 20일
Thanks for your help, Just accepted the other one before I seen this sorry..
Jan
Jan 2012년 9월 20일
No problem, Sam. Andrei's solution is fine and REGEXP is more powerful. I've posted the SSCANF(SPRINTF) approach, because it is simple and surprisingly fast.
shapes
shapes 2012년 10월 13일
Hi ppl,
My problem is in a way similar and not...i am reading a text file consisting of various lines of alpha-numeric strings... N010 G00 X0 Y0 Z0 N020 G01 X-10 Y10 Z-1 N030 G01 X20 Y40 Z-1 N040 G04 X3 Y3 Z10 M03
Now I need all numerical values of X, i.e. -10,20,3. The problem I am facing is that the strings are read from text file as 'cell' vector and i have to convert them to 'char' to use 'regexp' using '\w*X\w*'....this works, but doesnot allow the negative number to be read because it starts with a '-'. What to do now??? can anybody help??
shapes
shapes 2012년 10월 13일
for simplicity lets consider N040 G04 X-3 Y3 Z10 M03
K E
K E 2012년 11월 8일
Start a new question, and you are more likely to get an answer.

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

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by