Extract two floating point numbers from a string

조회 수: 15 (최근 30일)
dormant
dormant 2024년 7월 19일
편집: Stephen23 2024년 7월 20일
This should be easy, but I have no experience with MATLAB regexp or pattern and can't adapt the other answers about extracting numbers from a mixed string.
I want to get the latitude and longitude as floating point numbers from a string that looks like this:
23.047°S 67.782°W
The numbers will have 1-3 characters before the decimal point. An "S" or a "W" will produce a negative number.
Suggestions welcome.

채택된 답변

Himanshu
Himanshu 2024년 7월 19일
Hey Dormant,
I understand you are to extract latitude and longitude values as floating point number from a string. I was able to achieve the same. Here's my approach:
To extract latitude and longitude from a string like "23.047°S 67.782°W", I used regular expressions to identify and extract the numeric values and their respective direction indicators (N, S, E, W). The direction indicators are then used to assign the correct sign to the values, converting them to floating point numbers with negative values for 'S' and 'W'.
inputStr = '23.047°S 67.782°W';
% Regular expression to match numbers and directions
pattern = '([0-9]*\.[0-9]+)°([NSWE])';
% Extract matches using regexp
matches = regexp(inputStr, pattern, 'tokens');
latitude = 0;
longitude = 0;
% Iterate over matches and assign to latitude and longitude
for i = 1:length(matches)
value = str2double(matches{i}{1});
direction = matches{i}{2};
if direction == 'S'
latitude = -value;
elseif direction == 'N'
latitude = value;
elseif direction == 'W'
longitude = -value;
elseif direction == 'E'
longitude = value;
end
end
disp(['Latitude: ', num2str(latitude)]);
Latitude: -23.047
disp(['Longitude: ', num2str(longitude)]);
Longitude: -67.782
First, I defined the input string and the regular expression pattern to match the numerical values and their direction indicators. Using regexp, I extracted these matches into a cell array. Then, I looped through the matches, converting the string numbers to floating point and assigning the appropriate signs based on the direction indicators. Finally, I displayed the extracted latitude and longitude values.
Hope this helps!

추가 답변 (1개)

Stephen23
Stephen23 2024년 7월 19일
편집: Stephen23 2024년 7월 20일
T = '23.047°S 67.782°W 9.876°N 5.432°E' ;
V = sscanf(regexprep(T,{'(\S+)°[SW]','(\S+)°[NE]'},{'-$1','+$1'}),'%f')
V = 4x1
-23.0470 -67.7820 9.8760 5.4320
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by