Array Indicates msut be integer
1 view (last 30 days)
i have this code and run in matlab shows me thus error
(Array indices must be positive integers or logical values).
Please is there aby one can help
Error in Test (line 39)
d = sum(abs(SF(i)-VF));
D = [D d];
%% Finding Shortest Distance
SM = inf;
End = 1;
Guillaume on 2 Jun 2019
I would strongly recommend you do not use End as a variable name. It's too close to the keyword end. Use a more meanigful name anyway.
The problem with your code is simple. You set End to -1 before your loop. Inside the loop if a condition is true you'll then set End to a valid index. But if that condition is never true, you'll never change End and it will still be -1 when the loop finishes. Of course, -1 is not a valid index. So first thing is to add a check after the loop and react appropriately. At the very least:
EndIndex = -1; %use a better variable name than End
for i = 1:numel(D) %prefer numel over length
if %some check
End = -1;
assert(End > 0, 'if statement was never true. Code is not designed to cope with this case');
detected_class = UID(End);
The above issue is compounded by problems with your if test. I'm not sure which of the two versions you've posted is the one you're actually using. I'm assuming it's the first one because the second has many problems (e.g. mix up of d and D). Assuming your if test is:
There are 2 problems. First a<b<c doesn't do what you think. It compares a to b and results in either true (1) or false(0). It then compares that 0 or 1 to SM. As Star already told you, the proper way to write the comparison you mean is
if D<i & i<SM
The second issue is that D is a vector so D<i returns a vector of true and false values, not a scalar logical. The if statement will only be true if all elements of the vector are true. I would suspect that's never the case and hence why End stays at -1.
I'm actually not sure what you're trying to do here, so can't tell you how to fix that. It's very strange that you're comparing an index into a vector to the actual values of that vector.