Help using the arrayfun() function to apply strsplit() to all entries in a string array
19 views (last 30 days)
Show older comments
I'm trying to wrap my head around how the arrayfun() function works and would greatly appreciate some help with a specific example:
I have a string array of weather data.
weather_strings =
10×1 string array
"UTC,2140991,49.0"
"UTC,2140992,49.1"
"UTC,2140993,49.1"
...
I need to extract the values after the second comma (temperatures) as a 1x10 matrix of doubles, [49.0, 49.1, 49.1, ...].
I've figured out a clunky way to do this for a single entry (please let me know if there's a better way).
weather_string = weather_strings(1) % extract only the first entry
weather_string_split = strsplit(weather_string, ',') % apply strsplit() to split on commas
weather_string_split_trim = weather_string_split(:,3) % extract only 3rd column
weather_num_trim = str2num(weather_string_split_trim) % convert from string to double
But I can't seem to figure out how to use arrayfun() to apply that to every entry. I've tried:
weather_strings_split = arrayfun(strsplit(weather_strings,','), weather_strings) % apply stringsplit to split on commas, for all elements?
which gives the error message:
Error using strsplit (line 80)
First input must be either a character vector or a string scalar.
Error in test_window (line 17)
weather_strings_split = arrayfun(strsplit(weather_strings,','), weather_strings)
I'm probably missing something painfully obvious. What is it? I'm still somewhat of a beginner at coding, so I welcome you to explain it to me like I'm 5 years old.
Alternatively, if there's a clever way to extract these numbers directly from this data table (which came directly from a webread() function), I'd love to hear it. Var3 is a cell array.
weather_data_table =
10×3 table
Var1 Var2 Var3
__________ ________ __________________
2018-11-26 17:41:25 'UTC,2140991,49.0'
2018-11-26 17:42:27 'UTC,2140992,49.1'
2018-11-26 17:43:28 'UTC,2140993,49.1'
...
Again, the goal is to get just the last numbers after the second comma of Var3 into a 1D matrix.
Thanks in advance!
0 Comments
Accepted Answer
Star Strider
on 26 Nov 2018
Try this:
for k1 = 1:size(weather_strings,1)
Col3(k1,:) = str2double(regexp(weather_strings{k1}, '\d*\.\d*', 'match'));
end
Col3 =
49.0000
49.1000
49.1000
The loop is necessary because regexp is not vectorised. It can only handle one srting at a time.
6 Comments
More Answers (1)
Andrei Bobrov
on 28 Nov 2018
Edited: Andrei Bobrov
on 28 Nov 2018
In R2016b:
>> weather_strings = string({'UTC,2140991,49.0'
'UTC,2140992,49.1'
'UTC,2140993,49.1'})
weather_strings =
3x1 string array
"UTC,2140991,49.0"
"UTC,2140992,49.1"
"UTC,2140993,49.1"
>> str2double(regexp(C,'(\d+\.)?\d+$','match','once'))
ans =
49
49.1
49.1
>>
0 Comments
See Also
Categories
Find more on Cell Arrays 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!