Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore " character when using textscan() in MATLAB

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!

like image 966
Maddy Avatar asked Mar 14 '11 18:03

Maddy


People also ask

What does Textscan do in Matlab?

The textscan function converts the empty value in C{4} to -Inf , where C{4} is associated with a floating-point format. Because MATLAB® represents unsigned integer -Inf as 0 , textscan converts the empty value in C{5} to 0 , and not -Inf .

How do you read a text file in Matlab?

Use fopen to open the file, specify the character encoding, and obtain the fileID value. When you finish reading, close the file by calling fclose(fileID) . A = fscanf( fileID , formatSpec , sizeA ) reads file data into an array, A , with dimensions, sizeA , and positions the file pointer after the last value read.


1 Answers

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]
like image 113
gnovice Avatar answered Oct 17 '22 00:10

gnovice