MATLAB: Read .csv file with whitespace in complex number using textscan

complex numberstextscanwhitespace

I've got several .csv files with complex numbers delimited by commas. Example:
-0.0614049146709751 - 0.967215853912349i,-0.181447681051604 - 0.950981306143405i
Unfortunately the complex numbers in the files have whitespaces between the real and imaginary parts. This causes trouble when using textscan with format specifier %f%f. It returns the following error (when reading a real file with more inputs than 2 complex numbers and a format specifier of %f matching the number of inputs):
Error using textscan
Mismatch between file and format string.
Trouble reading 'Numeric' field from file (row number 1, field number 3) ==> - 0.967215853912349i,-0.181447681051604 -
0.950981306143405i,-0.290439723735331 - 0.922256442301523i,-0.409254287788005 - 0.874527909680631i,-0.541371606889636 -
0.797029055539859i,-0.694965707267823 ...
I've come up with the following solutions:
  1. Manually search and replace ' + ' and ' – ' in each file outside matlab.
  2. Read the data as strings, remove the whitespaces and convert to complex numbers in matlab.
Is there a better way to make textscan ignore those whitespaces?
Thanks in advance!

Best Answer

You can do all in Matlab by first reading full file as char array and doing a string replacement for the ill-formed blank between the plus/minus sign and the imaginary value and then parsing from memory.
>> textscan(strrep(l,'- ','-'),repmat('%f%f',1,2),'delimiter',',')
ans =
[-0.0614] [0 - 0.9672i] [-0.1814] [0 - 0.9510i]
>>
Or, if the file isn't all that big, just scan thru via fgetl and do line-by-line.
Alternatively, while I'm absolutely inept at writing the right pattern, regexp can do the field selection/cleanup as well.