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

前端 未结 3 1362
忘了有多久
忘了有多久 2020-11-21 06:08

The following error occurs quite frequently:

Subscript indices must either be real positive integers or logicals

I have found ma

3条回答
  •  一整个雨季
    2020-11-21 06:35

    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

提交回复
热议问题