Question

I am using textscan to read data from a file. The data being read is:

"ABC",0.156
"DEF",0.125
"GHI",0.101

My code is - data = textscan(fid, '%s %f', 'Delimiter', ',');

data{1} come as

'"ABC"'
'"DEF"'
'"GHI"'

I want the data{1} as -

'ABC'
'DEF'
'GHI'

Finally, how can I have the answer as

data = 
'ABC' [0.156];
'DEF' [0.125];
'GHI' [0.101];

instead of using data{1} and data{2}. Thanks!

Was it helpful?

Solution

There are actually two ways to ignore the " characters when reading your strings. As per the TEXTSCAN documentation, you can use the %q format instead of the %s format:

data = textscan(fid,'%q %f','Delimiter',',');

Or you can read the strings using the %s format and remove the " characters from data{1} using the function STRREP:

data{1} = strrep(data{1},'"','');

Then you can use the function NUM2CELL to convert the array of numeric values in data{2} to a cell array so that you can concatenate it with the cell array of strings in data{1}:

>> data = [data{1} num2cell(data{2})];

data =

    'ABC'    [0.1560]
    'DEF'    [0.1250]
    'GHI'    [0.1010]

OTHER TIPS

In order to get rid of the double quotes use

data = textscan(fid, '%q %f', 'Delimiter', ',');

where %q does the magic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top