Indexing error in function code.

33 views (last 30 days)
Jim Oste
Jim Oste on 23 Feb 2015
Commented: dpb on 23 Feb 2015
I have the following function:
function [ r ] = ost_approx_rate_conv( h_1,B )
n = 1:length(B);
k = 2:1:length(B);
h = zeros(size(n));
h(k+1) = h(k-1)/2;
h(1) = h_1;
h = logical(h);
r(h) = log((B(2*h)-B(2*h))/(B(h)-B(2*h)))/log(2);
and when I try to run it I get "Subscript indices must either be real positive integers or logicals." error for my r(h) term. How exactly would I remedy this?
  1 Comment
dpb
dpb on 23 Feb 2015
Need to first define what it is you're trying to do. This is peculiar at best and undoubtedly not what you intend but I can't tell what is wanted from the code alone.
For example, k is vector of integers from 2:length(B) and h is a zero-valued vector of length(B) but then you assign the 3rd thru (N+1)th positions to the values from the 1:(N-1)th (dividing by 2, but zero/2 is still zero, so all you've really done in the end is
h=zeroes(1,length(B)+1);
h(1)=h_1;
after all that.
The explicit cause of the error, however, is that when you write
B(2*h)
despite have previously converted h to logical array, that you've subsequently multiplied by 2 means its numeric and most (if not all) the entries are zero. Matlab arrays are one-based so 0 is not either a positive integer nor a logical.
BTW, the expression
log((B(2*h)-B(2*h))
is log(0) as the two terms are identical so this also is clearly not what you're intending but I've no kluw what that might be...

Sign in to comment.

Answers (2)

Andrew Newell
Andrew Newell on 23 Feb 2015
Edited: Andrew Newell on 23 Feb 2015
You'll get the same error with this code snippet:
h = logical([1 0]);
B(2*h)
or, for that matter, just
B(0)
The problem is that by multiplying h by 2, you're converting it back to a double precision number. So you have indices
2*h
ans =
2 0
and the second index is zero. As to how you might fix it, I can't suggest anything because I don't understand what you are trying to do.

Michael Haderlein
Michael Haderlein on 23 Feb 2015
You initialize h as zeros. k goes from 2 to length(B). The line
h(k+1) = h(k-1)/2;
remains all h as zeros (and I'm questioning if this line is doing what you want - extending h by one zero).
The line
h = logical(h);
sets all these zeros (only the first element of h might have been set nonzero) to false. However, the line
r(h) = log((B(2*h)-B(2*h))/(B(h)-B(2*h)))/log(2);
wants to check B(2*h). The multiplication of a double with a logical returns a double. In case of the logical being false, the double will be zero. So, finally, you ask for B(0) and that does not exist in Matlab.
I guess there are quite some operations here which are not intended. Maybe you might want read about logical indexing as a keyword. Also, you can explain the purpose of your code and we might be able to hint you to working code.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!