Перевод subscript indices must either be real positive integers or logicals

Ошибка MATLAB: индексы индексов должны быть либо натуральными целыми положительными, либо логическими

В настоящее время я запускаю свой код и обнаруживаю раздражающую проблему, о которой я действительно не знаю.

Функция, которую я разрабатываю, следующая:

И кровавая проблема возникает на этой линии:

говоря, что «индексы индексов должны быть либо натуральными целыми числами, либо логическими». ну, входная переменная «PriceMat» является ценовой матрицей 60×10, а «Символы» — строкой 10×1.

Еще один вопрос:) что конкретно означает «индексы индексов»?

MUCH заранее оценили xx

Позвольте решать ваши вопросы по очереди:

«Индексы индексов должны быть либо натуральными целыми числами, либо логическими». ну, входная переменная «PriceMat» является ценовой матрицей 60×10, а «Символы» — строкой 10×1.

Посмотрите на свою переменную CointPairs . Это результат использования команды find . Может быть случай, когда CointPairs создает пустую матрицу. Это связано с тем, что при запуске find может быть случай, когда в CointMatrix есть нет записи, где она равна 1 (или фактически не равна нулю). Если это так, то CointPairs будет фактически пустым, поскольку нет элементов, соответствующих требованиям.

Как таковая причина, по которой вы получаете эту ошибку, заключается в том, что вы пытаетесь выполнять операции с пустой, когда это не разрешено. Вам нужно переместить оператор if до CointPairs = [rows, cols]; . Таким образом, вы не получите никаких ошибок доступа. Другими словами, сделайте следующее:

Один незначительный комментарий, который у меня есть, заключается в том, что ваша выходная переменная out , но вы не назначаете ее нигде в своем коде. Это намеренно?

Еще один вопрос: что именно означают «индексы индексов»?

Индексы индексов — это те значения, которые вы используете для доступа к элементам в вашем массиве/матрице. Например, предположим, что ваша матрица:

Выполняя A(2,2) , мы получаем элемент 5. Строка 2 и столбец 2 называются индексом индекса. Индексы подразумевают более одного, поэтому вместо простой пары строк и столбцов вы можете использовать два массива элементов для доступа к строкам и столбцам вашей матрицы. Каждая пара соответствующих элементов в паре является индексом индекса.

В основном, это числа, которые вы используете для доступа к строкам и столбцам вашей матрицы. Вы можете обращаться к элементам только в матрицах/массивах, используя положительные числа (a.k.a. 1, 2, 3, 4. ) или логические операторы (т.е. true / false ). Пустая матрица, 0, отрицательные целые числа или числа с плавающей запятой не допускаются.

Поскольку вы получаете доступ к своей матрице, используя ни один из приведенных выше допустимых входов, вы получаете эту ошибку.

Источник

octave error: subscript indices must be either positive integers or logicals

I’m trying to sum the product of an indexed vector and an indexed matrix like this:

but I get the error:

What am I missing here?

EDIT: I just realized that I missed the _plus function to sum the generated sequences. It should look like this:

I still get the same error though.

2 Answers 2

The error message explains what is wrong: you are trying to index an array with a number which is not a positive integer or logical. The only array indexing in your code is x_n(n) . And sure enough, the line n=[0:1:N-1] demonstrates that the index n is not positive, since 0 is not a positive number. Lesson: MATLAB/Octave always index from 1. I do suggest you real some tutorials as this is fundamental stuff which you’ll need to know.

Allow me to offer some critique of your code — since you admitted you were a newbie at this. First you create the vector

Which, incidentally, doesn’t need the square brackets and could be written as

Then you generate a vector x_n which, for the values given, will be all zeros ( sin(pi*n) ==0 for integer values of n ).

Next, you do something strange — you appear to be generating a symbolic sequence, looping a variable n which looks a lot like the array n you defined earlier. Not sure what to make of that — doesn’t seem like a great idea. Notice that even @jazzbassrob was confused by this — the fact that you got a «can’t index with zero» error wasn’t because of the value of your vector n , but because you were looping from 0..N-1 in the _seqgen command (not the same thing, although it happens to be the same values).

In that _seqgen expression, I see exp(k*n/N) which works because in this context n is the variable being stepped through 0..N-1 — if Matlab was looking at the earlier definition of n , it would throw another error because of a dimension mismatch (since * is the matrix multiplication operator and expects the second dimension of the first element to be = the first dimension of the second element).

A more standard way to do what you are trying to do would be

This does an element-by-element multiplication of the terms in x_n and the exp of a element-by-element product of k and n divided by N .

Note — whether this is actually «better» depends on what you want to do with the result (the above evaluates it).

Источник

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

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.

3 Answers 3

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:

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

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

Complicated occurrence of invalid index

I recommend working inside out. So first evaluate the most inner variable being indexed: d . It turns out that cell2mat():c , nicely evaluates to integers. Then evaluate b+mean(d(cell2mat():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

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

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

Источник

Оцените статью
( Пока оценок нет )
Поделиться с друзьями
Uchenik.top - научные работы и подготовка
0 0 голоса
Article Rating
Подписаться
Уведомить о
guest
0 Комментарий
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии