Using sscanf (or equivalent) to extract double from string.

조회 수: 14 (최근 30일)
James
James 2014년 11월 26일
답변: Stephen23 2014년 12월 1일
Let's say I have a string as follows:
string = '2.3A 4B C'
I want to apply a function that will output the following:
[2.3 4 1]
where these values are simply the "prefixes" (converted to doubles) of the letters specified within the string. One important note is that any letter lacking a prefix should output a 1.
My first thought was to use sscanf and include some condition for letters lacking prefixes, but it hasn't quite worked the way I'd like.
Any suggestions from the Matlab world?
Thanks!

채택된 답변

Stephen23
Stephen23 2014년 12월 1일
This solution uses regexp to detect the sequences of characters (possibly with leading digits and optional decimal fraction). It returns the numeric parts, which are then converted to floating point numbers. Any empty cells are given the value 1, then the whole thing is converted to a numeric array.
>> str = '2.3A 4B C';
>> A = regexp(str,'(\d+(\.\d+)?)?[A-Z]+','tokens');
>> A = [A{:}];
>> A = cellfun(@str2num,A,'UniformOutput',false);
>> A{cellfun('isempty',A)} = 1;
>> A = [A{:}]
A =
2.3 4 1
No loops, no cluttering up of the workspace... elegance is never overrated!

추가 답변 (1개)

James
James 2014년 11월 26일
Well, this seems to work. Elegance is overrated, right? aha
name = '2.3A 4B C';
letterIndex = regexp(name,'[A-Z]');
letterNum = 1;
floatLength = 0;
outVal = zeros(1,length(letterIndex));
for i = 1:length(name)
if i == letterIndex(letterNum)
if floatLength == 1
outVal(letterNum) = 1;
else
outVal(letterNum) = str2double(name((i-floatLength):(i-1)));
end
floatLength = 0;
letterNum = letterNum + 1;
else
floatLength = floatLength + 1;
end
end

카테고리

Help CenterFile 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