Extract two floating point numbers from a string
17 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Himanshu
on 19 Jul 2024
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)]);
disp(['Longitude: ', num2str(longitude)]);
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!
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!