Index in position 1 exceeds array bounds (must not exceed 1818)

1 visualización (últimos 30 días)
Amelia Carr
Amelia Carr el 11 de Mayo de 2020
Editada: Stephen23 el 11 de Mayo de 2020
I am running my code on MATLAB and I am getting an error message: "Index in position 1 exceeds array bounds (must not exceed 1818)".
The error messages comes from: "matrix_load(i,number)=all_file_matrix(i,2)".
What does "Index in position 1 exceeds array bounds" mean?
and how can I solve this?
I have attached my txt files.
Here is my code:
%% Calculate average of experimental data
file_name = {'Sample1','Sample2','Sample3','Sample4','Sample5'};
numExperiments=5;
rows=1821;
matrix_load = zeros(rows,numExperiments);
matrix_disp = zeros(rows,numExperiments);
for number=1:numExperiments
all_file_matrix=load(fullfile(pathName,sprintf('Sample%d.txt',number)));
for i=1:rows
matrix_load(i,number)=all_file_matrix(i,2);
matrix_disp(i,number)=all_file_matrix(i,1);
end
end
average_load = mean(matrix_load,2);
average_disp = mean(matrix_disp,2);

Respuestas (2)

KALYAN ACHARJYA
KALYAN ACHARJYA el 11 de Mayo de 2020
Editada: KALYAN ACHARJYA el 11 de Mayo de 2020
Your all_file_matrix(Sample1.txt) have 1818 rows and you are trying to access rows(i)=1821.

Stephen23
Stephen23 el 11 de Mayo de 2020
Editada: Stephen23 el 11 de Mayo de 2020
"What does "Index in position 1 exceeds array bounds" mean?"
Here are the index positions for subscript indexing:
anyarray(position1, position2, position3, position4, ...)
The errror message tells us that you have used an index value in position 1 which is larger than the array actually has. The cause is easy to identify when we look at your file data: all of the files have 1818 rows, except Sample2.txt which has 1821. I guess that is why you preallocated the output matrix with 1821 rows, but you also need to consider what will happen here (where the error actually occurs):
all_file_matrix(i,2)
all_file_matrix(i,1)
For any of the files with only 1818 rows, what happens when i=1819? (hint: because the index exceeds the array size an error will be thrown).
The fix is to only refer to rows that actually exist, e.g.:
N = 5; % number of experiments
R = 1821; % max number of rows
matrix_load = zeros(R,N);
matrix_disp = zeros(R,N);
for k = 1:N
F = sprintf('Sample%u.txt',k);
M = dlmread(F);
S = size(M);
matrix_load(1:S(1),k) = M(:,2);
matrix_disp(1:S(1),k) = M(:,1);
end % ^^^^^^ this indexing fixes the error
You also need to consider that the zeros at the bottom of the columns will be included in your mean calculations: you need to decide if that makes sense for what you want to achieve.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by