MATLAB: Error: index exceeds matrix dimensions.

cellarraysfileinputfileoutput

clear cInfo;
fid = fopen('wages.txt','rt');
count = 0;
while not(feof(fid))
cInfo = textscan(fid,'%d %s %f',1);
cont = cont +1;
employee(cont).id = cInfo{1}(1);
employee(cont).category = cInfo{2}{1};
employee(cont).salary = cInfo{3}(1);
end;
fclose(fid);
It was just one part of the code, I get the error in 'employee(cont).id = cInfo{1}(1);'
Content of 'wages.txt':
34 Agent 1500
74 Manager 2000
66 Manager 1700
99 Programmer 1500

Best Answer

feof() never predicts end of file. feof() is not true until you try a read and it fails: feof() never tells you that if you were to read then it would fail. When you reach end of file, the textscan is returning empty values, which you are not testing for.
In a case like this you should textscan() all of the values at the same time and then do the assignments after the loop.
fid = fopen('wages.txt','rt');
cInfo = textscan(fid, '%d %s %f');
fclose(fid);
nWage = length(cInfo{1});
employee(nWage) = struct('id', [], 'category', [], 'salary', []); %initialize to full length
for cont = 1 : nWage
employee(cont) = struct('id', Cinfo{1}(cont), 'category', Cinfo{2}{cont}, 'salary', Cinfo{3}(cont));
end