I have a string which is thousands of characters, meaning there are about 300 columns in it separated by whitespace. Some of the columns are character strings and most are integers/floats. The problem is that I need to read only a few of the columns for example the first column, the 5th column, the 37th column, the 117th column, and the 152nd column and the ignore the rest of the string. The only way I see it using sscanf in MATLAB is to do something like
mystring = '245 0.00000000 2456171.50000000 1030492816.000 5.14501001 1 IG 5 -1.188022 .... 5.032154 90';
params = sscanf(mystring, '%f %*f %*f %f %*f %f %*s %f %*f ... %f %*[^\n]')'];
which seems completely ridiculous to me since I need to have %f or %*f 152 times at least if I want to read in the 152nd column. So my question is what is the most efficient way of doing this using sscanf in MATLAB? If I can find something robust and easy-to-change that would be amazing. For example, if tomorrow I decide that I only need the first, fifth, and the hundredth column where the total number of columns that I need and the columns themselves have changed, then it should be easy to specify. If too much work, no worries. Any tricks?
The entire string has floats and strings mixed in but the columns that I need are always only floats/integers which MATLAB returns to params as doubles. Thanks in advance!
You could use strsplit to split your string and then access the array element that you are interested in.
mystring = '245 0.00000000 2456171.50000000 1030492816.000 5.14501001 1 IG 5 -1.188022 .... 5.032154 90';
split = strsplit(mystring);
If your version of MATLAB is too old and strsplit isn't included, then it can be downloaded from MATLAB central.
Then you could use str2num or str2double to turn each string you are interested in into a number.
col5 = str2double(split(5));
% or
mycols = str2double(split([5 37 117]));
strsplit reference
str2num reference
str2double reference
Here is a piece of code that replicates %*f using repmat (with cells). It then changes the %*f into %f at the provided indexes, and finally transform the cells into a char vector.
f_star_nb = 20;
f_ind = [2 6 9];
f = repmat({'%*f'}, f_star_nb, 1)
f(f_ind) = {'%f'};
f = [f{:}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With