1
votes

How can I read a textfile containing the following text in matlab?

B4070IC05.tif,11
B4070IC06.tif,11,15,16,6,7 
B4070IC07.tif,13,14,4,18,9
B4070IC08.tif,10,7
B4070IC09.tif,4,22,7
B4070IC10.tif,14,15,19,20,24,29,9
B4070IC11.tif,10,11,20,21
B4070IC12.tif,13,14,5,9

I don't know the number of columns of text.

Is there a way to put these data in a cell matrix? how can I print the cell matrix after the data load?

1

1 Answers

1
votes

You can use textscan for this. Make sure that the number of %f-s is long enough to cover the longest series of values in your file. If all numeric values are integer, you could also use for instance `%d' (see textscan for more details).

fid = fopen(filename);
A = textscan(fid,'%s %f %f %f %f %f %f %f','delimiter',',');
fclose(fid);

The result is a cell array, with the first column the strings 'blabla.tif' and the second up to last column the numeric values. If a value is not present in the file, it equals NaN.

Accessing the j-th value of the i-th column is done by A{i}(j).


By the way, the last line in the file is not appended with NaNs, like the other lines. This means that combining the result into a cell array is not directly possible: the last few arrays are (might be) shorter than the first. I did not find an obvious fix for that, so we have to do that manually:

idx = find(diff(arrayfun(@(idx)numel(A{idx}),1:numel(A))));
cA = [A{1} num2cell([horzcat(A{2:idx}) [horzcat(A{idx+1:end});nan(1,numel(A)-idx)]])];