Index exceeds the number of array elements (0) when finding values ​​in a loop?

1 view (last 30 days)
There is a very complex cycle. In it I create a vector of values, in a loop inside the loop I do my calculations, but for these calculations I need the first value in the vector?
while (~feof(fileID)) && (ftell(fileID)<fsize)
%
j=j+1;
a=fread(fileID,[1,1],'uint16');
b=fread(fileID,[1,1],'uint16');
c=fread(fileID,[1,1],'uint16');
%
A(j)=a; % all arrays of sizes in 300
B(j)=b; %
C(j)=c %
% A = [ 0 0 20 0....0 0 20 0]
% B = [ 3 4 2 4....4 4 2 4]
x=find(A==20); % size 100
x1=B(x(1)); % I am getting an error in this section.
if channel==2 % right now 2 is entered manually but i want to make it automatic
....
i=i+1;
end
end
Index exceeds the number of array elements (0).
Error in ABCpart021722 (line 268)
x1=B(x(1));
Is it possible to bypass this error? I will be glad for any help.

Answers (1)

Walter Roberson
Walter Roberson on 17 Feb 2022
A(j)=a; % all arrays of sizes in 300
Did you pre-initialized A? If you did, then since you have not finished writing in it yet, then some A entries might be 0
x=find(A==20); % size 100
but there you are comparing against all of A, including locations that are possibly not written to yet.
If you are instead allowing A to grow in-place (which is inefficient if you can guess a maximum size), then consider that on the very first iteration, the value you stored into A(1) might not happened to be 20, so A==20 might be empty, leaving x empty. But later you x1=B(x(1)) which is a problem if x is empty.
You should not be trying to index using x(1) unless you have found at least one 20. And once you do find at least one 20 you are always going to be indexing with the same location, always using the same value out of B every time after you found the first A, since the 20 is going to stay in A once it gets assigned the first time. You are not looking at the "most recent" location, you are always using the "first" location.... are you sure that is what you want?

Products

Community Treasure Hunt

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

Start Hunting!