0

I used this :

weights=fopen('indices.txt');
weights=textscan(weights, '%d %d %d %d %d %d %d')

but this only reads the first line of my file. my file looks like this :

0 90 100 5 0 0 0 (class)
19 5 0 0 0 0 0 (class2)
5 5 0 0 0 0 0 (class3)
-10 -5 0 0 0 0 0 (class4)

And I don't need what's in the brackets

Thanks a lot !

Lay
  • 249
  • 1
  • 3
  • 15

2 Answers2

2

For this case, you can do the following:

fid = fopen('indices.txt');
num_ints = 7;
num_rows = 4;

format = [repmat('%d ', 1, num_ints), '%s'];
weights = textscan(fid, format, num_rows);
weights = [weights{1:num_ints}];
fclose(fid);

The downside of course is that you have to know the number of rows that you're reading beforehand. You could try calling textscan in a loop, but that doesn't seem to be how it's meant to be used (and I would rather use fgetl instead if I'm trying to read the file line-by-line).

alrikai
  • 4,123
  • 3
  • 24
  • 23
1

Use the following:

fh = fopen('indices.txt');
resC = textscan(fh, '%d %d %d %d %d %d %d %s', 1000);
res = cell2mat(resC(1:7))
fclose(fh);

textscan will only read (and return) up to the available number of lines. Note however, that textscan allocates memory for the number of lines you provide (1000 here), so you want to choose something "wise" there.

gzm0
  • 14,752
  • 1
  • 36
  • 64