index exceeding array bounds

조회 수: 1 (최근 30일)
Tim Johansson
Tim Johansson 2020년 10월 28일
답변: Star Strider 2020년 10월 28일
For some reason i exceed array bounds but i cant seem to figure out why.
The code looks like this:
1 for i = 1:length(rawData.sub3.epochs.run)
2 for j = 1:length(rawData.sub3.epochs.run{i}.movement)
3 k=ceil(j/4)
4 if rawData.sub3.label{i}.data(j,3) == 0
5 classData.sub3.movement.right{i,k}=rawData.sub3.epochs.run{i}.movement{j}
6 elseif rawData.sub3.label{i}.data(j,3) == 1
7 classData.sub3.movement.up{i,k}=rawData.sub3.epochs.run{i}.movement{j}
8 elseif rawData.sub3.label{i}.data(j,3) == 2
9 classData.sub3.movement.left{i,k}=rawData.sub3.epochs.run{i}.movement{j}
10 elseif rawData.sub3.label{i}.data(j,3) == 3
11 classData.sub3.movement.down{i,k}=rawData.sub3.epochs.run{i}.movement{j}
12 end
13 end
14 end
Where rawData is a struct that contains run(a 1x20 cell array) which each contain a 1x20 cell array (but in one case a 1x10).
The error i get is
"Error in code (line 4), if rawData.sub3.label{i}.data(j,3) == 0"
"Index in position 1 exceeds array bounds (must not exceed 10)."
but the code should in my eyes be able to handle the change in array size.
Furthermore the error seems to happen before it hits run{11} which is the 1x10 cell array.
any help would be appriciated.

답변 (1개)

Star Strider
Star Strider 2020년 10월 28일
One option would be to test ‘j’ against the number of rows in the matrix-of-interest, something like this:
for j = 1:length(rawData.sub3.epochs.run{i}.movement)
k=ceil(j/4)
m = min(j,size(rawData.sub3.label{i}.data(:,3),1));
then:
if rawData.sub3.label{i}.data(m,3) == 0
↑ ← CHANGE INDEX VARIABLE
and so for the rest of the references to it. That should keep the index from referencing the array elements that do not exist. Other changes to the code as well may be necessary. It might also be worthwhile to consider using break to exit the ‘j’ loop if j>m.
I cannot test this with your data, so I am posting it as UNTESTED CODE.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by