tarik
tarik

Reputation: 153

Matlab: Converting a string to a rational number

How to convert the rational number strings to numbers from a text file having musical notes listed with names and timings.

For instance;

La,1/8 
La,1/8 
La,1/8 
La,1/8 
Si,1/4

Reading the file into Matlab and get the lines one by one.

fid=fopen('file.txt');
while 1
  tline = fgetl(fid);
  if ~ischar(tline), break, end
  %disp(tline)
  split = strsplit(tline,',');
  note=split(1);
  timing=str2num(split(2));
end
fclose(fid);

I can get the first data which is the musical note as string. The problem is the timing part. str2num can convert strings to numbers but when it's a rational number as in the example above, it returns NaN. How to get these data, the first one as string and the second as rational number?

Upvotes: 3

Views: 262

Answers (2)

Matthew Gunn
Matthew Gunn

Reputation: 4519

Another approach to consider (less low-level file manipulation)

If you have a file music.txt that's a csv:

Note, Timing
La, 1/8
Si, 1/4

You could read it into a Matlab table and convert to your timing column to a double with:

t         = readtable('music.txt');
t.TimeNum = cellfun(@str2num, t.Timing); % Apply str2num to each entry 
                                         % of t.Timing cell array

Then your table t would be:

  Note    Timing    TimeNum 
  ____    ______    _____

  'La'    '1/8'      0.125
  'Si'    '1/4'      0.25

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112689

I think the problem is that strsplit returns a cell array of strings:

>> tline = 'La,1/8'; %// example line
>> split = strsplit(tline,',')
split = 
    'La'    '1/8'

and you can't apply str2num on a cell:

>> str2num(split(2))
Error using str2num (line 32)
Requires string or character array input. 

But you can apply it on the cell's contents, which is a string:

>> str2num(split{2})
ans =
   0.125000000000000

Upvotes: 3

Related Questions