Subscript indices must either be real positive integers or logicals, generic solution
Asked Answered
T

3

41

The following error occurs quite frequently:

Subscript indices must either be real positive integers or logicals

I have found many questions about this but not one with a really generic answer. Hence I would like to have the general solution for dealing with this problem.

Throat answered 18/11, 2013 at 17:32 Comment(3)
I suggest expanding this QA with two other very closely related errors. Consider: >> mean=1:4; >> mean(12) Index exceeds matrix dimensions. >> mean(12); Attempted to access mean(12); index out of bounds because numel(mean)=4. First is the "Index exceeds matrix dimensions" error when accidentally naming a variable as a builtin and then trying to use the builtin as a function. The second is a bizarre variation that simply provides more details on the same mistake.Maros
@Maros Though the errors are related, the main goal of this post is to help people who get this specific error message. Of course it may be a good idea to find/create a good reference question and answer for each common error message.Throat
Good point. It's best to keep it focused, although the solutions are much the same (point 2. below).Maros
T
62

Subscript indices must either be real positive integers or logicals

In nearly all cases this error is caused by one of two reasons. Fortunately there is an easy check for this.

First of all make sure you are at the line where the error occurs, this can usually be achieved by using dbstop if error before you run your function or script. Now we can check for the first problem:

1. Somewhere an invalid index is used to access a variable

Find every variable, and see how they are being indexed. A variable being indexed is typically in one of these forms:

variableName(index,index)
variableName{index,index}
variableName{indices}(indices)

Now simply look at the stuff between the brackets, and select every index. Then hit f9 to evaluate the result and check whether it is a real positive integer or logical. Visual inspection is usually sufficient (remember that acceptable values are in true,false or 1,2,3,... BUT NOT 0) , but for a large matrix you can use things like isequal(index, round(index)), or more exactly isequal(x, max(1,round(abs(x)))) to check for real positive integers. To check the class you can use class(index) which should return 'logical' if the values are all 'true' or 'false'.

Make sure to check evaluate every index, even those that look unusual as per the example below. If all indices check out, you are probably facing the second problem:

2. A function name has been overshadowed by a user defined variable

MATLAB functions often have very intuitive names. This is convenient, but sometimes results in accidentally overloading (builtin) functions, i.e. creating a variable with the same name as a function for example you could go max = 9 and for the rest of you script/function Matlab will consider max to be a variable instead of the function max so you will get this error if you try something like max([1 8 0 3 7]) because instead of return the maximum value of that vector, Matlab now assumes you are trying to index the variable max and 0 is an invalid index.

In order to check which variables you have you can look at the workspace. However if you are looking for a systematic approach here is one:

For every letter or word that is followed by brackets () and has not been confirmed to have proper indices in step 1. Check whether it is actually a variable. This can easily be done by using which.


Examples

Simple occurrence of invalid index

a = 1;
b = 2;
c = 3;
a(b/c)

Here we will evaluate b/c and find that it is not a nicely rounded number.

Complicated occurrence of invalid index

a = 1;
b = 2;
c = 3;
d = 1:10;
a(b+mean(d(cell2mat({b}):c)))

I recommend working inside out. So first evaluate the most inner variable being indexed: d. It turns out that cell2mat({b}):c, nicely evaluates to integers. Then evaluate b+mean(d(cell2mat({b}):c)) and find that we don't have an integer or logical as index to a.

Here we will evaluate b/c and find that it is not a nicely rounded number.

Overloaded a function

which mean 
% some directory\filename.m

You should see something like this to actually confirm that something is a function.

a = 1:4;
b=0:0.1:1;
mean(a) = 2.5;
mean(b);

Here we see that mean has accidentally been assigned to. Now we get:

which mean
% mean is a variable.
Throat answered 18/11, 2013 at 17:32 Comment(1)
Great answer. You might want to add a specific caveat for the usage of i and j as loop variables, as they are already the imaginary unit before assigning them. (This is not to advocate against the use of i and j as variable names, merely as an observation since I often see one of those being the culprit of this error.)Gorlin
L
5

In Matlab (and most other programming languages) the multiplication sign must always be written. While in your math class you probably learned that you can write write a(a+a) instead of a*(a+a), this is not the same in matlab. The first is an indexing or function call, while the second is a multiplication.

>> a=0

a =

     0

>> a*(a+a)

ans =

     0

>> a(a+a)
Subscript indices must either be real
positive integers or logicals.
Leighannleighland answered 13/12, 2015 at 19:16 Comment(1)
Though this case is implicitly covered in point 1 of my answer, I like the additional example of how it can occur. Adding a comment here to help people who are searching for Subscript indices must either be real positive integers or logicals when doing multiplication.Throat
O
4

Answers to this question so far focused on the sources of this error, which is great. But it is important to understand the powerful yet very intuitive feature of matrix indexing in Matlab. Hence how indexing works and what is a valid index would help avoid this error in the first place by using valid indices.

At its core, given an array A of length n, there are two ways of indexing it.

  1. Linear indexing: with subset of integers from 1 : n (duplicates allowed). 0 is not allowed, as Matlab arrays are 1-based, unless you use the method below. For higher-dimensional arrays, multiple subscripts are internally converted into a linear index, although in an efficient and transparent manner.
  2. Logical indexing:wherein you use a n-length array of 0s and 1s, to pick those elements where indexing is true. In this case, unique(index) must have only 0 and 1.

So a valid indexing array into another array with n number of elements ca be:

  1. entirely logical of the same size, or
  2. linear with subsets of integers from 1:n

Keeping this in mind, invalid indexing error occurs when you mix the two types of indexing: one or more zeros occur in your linearly indexing array, or you mix 0s and 1s with anything other than 0s and 1s :)

There is tons of material online to learn this including this one: http://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html

Outofdoor answered 31/12, 2015 at 16:57 Comment(2)
It is a nice explanation in general, and I don't want to discourage you, but it does seem that the part where you actually answer the specific question is already covered. As such I think this should actually be a comment rather than an answer. (I didn't flag it as it is way too long to be transferred to a comment, but keep that in mind for future posts).Throat
Thanks Dennis. I thought about your point whether I should waste my time (which might waste other people's time if its not adding much), and decided this would improve people's ability in the future. if there is any, perhaps you can move it to some meta place for tutorials/tips for matlab as this explanation is at the core of an important feature.Outofdoor

© 2022 - 2024 — McMap. All rights reserved.