Cesar
Cesar

Reputation: 91

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:

k=[0:1:N-1]  
n=[0:1:N-1]  
x_n = sin(pi*n)  
N = size(x_n,2)  
_seqgen(x_n(n)*exp(k*n/N), n, 0..N-1)  

but I get the error:

error: subscript indices must be either positive integers or logicals  

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:

k=[0:1:N-1]  
n=[0:1:N-1]  
x_n = sin(pi*n)  
N = size(x_n,2)  
_plus(_seqgen(x_n(n)*exp(k*n/N), n, 0..N-1))  

I still get the same error though...

Upvotes: 3

Views: 55271

Answers (2)

Floris
Floris

Reputation: 46365

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

n = [0:1:N-1];

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

n = 0:N-1;

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

mySum = sum(x_n.*exp(k.*n/N));

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).

Upvotes: 2

devrobf
devrobf

Reputation: 7213

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.

Upvotes: 10

Related Questions