Index in position 2 exceeds array bounds. Index must not exceed 2?

7 views (last 30 days)
I am trying to run a FOR LOOP concerning 5 years of wave parameter data (each year is a different data file, each data file ranges from 1st Jan to 31st Dec) but I keep on getting the error:
Index in position 2 exceeds array bounds. Index must not exceed 2.
Everything before the "H" variable seems to work, although my full data file should be 17520x34 array but the data array produced is only 1x1. Here is my code that I have been using and editing bit by bit (the FOR LOOP is not finished) to see if each variable works:
close all
clear all
clc
%Load in the data
fpath=uigetdir;
files=dir([fpath '\*.csv']);
files=char(files.name);
%for loop to go through the variable files, creating variables for wave
%height (Hmax [H])), max period (Tmax [T]), and geographical direction in
%degrees (Directiondeg [direction]). Using textscan function to read the
%data files.
for n=1:size(files,1)
fid=fopen([fpath '\' files(n,:)]);
data{n}=textscan(fid, ['%s' repmat('%f', 1,34)],'Delimiter',',','CollectOutput',1, 'Headerlines',1);
fclose(fid);
data{1,n}{1,1}=datetime(data{1,n}{1,1}, "InputFormat","dd-MMM-uuuu HH:mm:ss");
time=data{1,n}{1,1};
%up to this line appears to work.
H=data{n}(:,5);
end
and here is what appears in my workspace:
ans 0
data 1x1 cell
fid 3
files 5x29 char
fpath 'C:\users\...
n 1
time 17520x1
I'm quite new to matlabs so its probably a stupid question, but I cannot identify the issue with the code. Thank you for any help.

Answers (2)

Star Strider
Star Strider on 25 Nov 2022
See my Comment to your earlier Question.

Image Analyst
Image Analyst on 25 Nov 2022
No, you should not use char. Not sure who gave you that bad way of doing things but you should do it like in the FAQ:
close all
clear all
clc
%Load in the data
fpath = uigetdir;
files = dir(fullfile(fpath, '\*.csv'));
%for loop to go through the variable files, creating variables for wave
%height (Hmax [H])), max period (Tmax [T]), and geographical direction in
%degrees (Directiondeg [direction]). Using textscan function to read the
%data files.
for n = 1 : numel(files)
% Get the file name.
fullFileName = fullfile(files(n).folder, files(n).name);
fprintf('Processing "%s".\n', fullFileName)
% Open and process the file.
fid=fopen(fullFileName);
data{n}=textscan(fid, ['%s' repmat('%f', 1,34)],'Delimiter',',','CollectOutput',1, 'Headerlines',1);
fclose(fid);
% Process the data we retrieved.
data{1,n}{1,1}=datetime(data{1,n}{1,1}, "InputFormat","dd-MMM-uuuu HH:mm:ss");
theTime = data{1,n}{1,1};
H = data{n}(:,5);
end

Community Treasure Hunt

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

Start Hunting!