Index exceeds matrix dimensions.

4 visualizzazioni (ultimi 30 giorni)
Jovos
Jovos il 18 Feb 2016
Risposto: Walter Roberson il 18 Feb 2016
Hi, I'm trying to read the raw data from a txt file. Read the file as an array of strings. Then transfer string to num and get the year data. But it shows that the index exceeds matrix dimensions. Anyone help?
filename = input('Please enter the file name: ');
fid01 = fopen(filename,'r');
for i = 6 : 414
line = fgets(fid01);
z = strread(line,'%s');
year = str2num(z{1});
disp(year)
end
[EDITED, Jan, Code formatted]

Risposta accettata

Walter Roberson
Walter Roberson il 18 Feb 2016
You have an empty lines in the input, and lines that have only blanks. fgets() is going to return each line including the line terminator. The strread() with '%s' format is going to return an empty cell array on those lines.
I would remind you that
for i = 6 : 414
line = fgets(fid01);
...
end
contains no instructions to MATLAB that the line to be fetched is the line number the corresponds to "i".
What you should do is, before the "for i = 6" loop, add a loop
for i = 1 : 5
line = fgets(fid01);
end
to read through (and ignore) lines 1 to 5. Then each time you read a line in "for i = 6 : 414" the line number will implicitly synchronize with the value of the "i" variable.

Più risposte (0)

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by