MATLAB: Index exceeds array bound help

exceed

Hello, I'm trying to have decimals in the for loop, I've used this way to do it but it showed me Index exceeds array bound. Is there any other way to have decimals in for loop too?
In this, magnew is 900 values from 3.1 to 7.9.
zz=1:0.1:10;
for z=1:91
a(z)=length(find(magnew>=(zz(z)) & magnew<(zz(z+1))))/(length(magnew));
end

Best Answer

length(zz) is 91, so up to zz(91) exists.
In your for loop you go z=1:91 so z can become 91. You index zz(z+1) so you try to index up to z(91+1) = z(92) which does not exist.
By the way, there is a way to make your calculation more efficient
Consider your sub-expression length(find(LOGICAL)) . find() is going to return one index for each location where LOGICAL is true, and length() of that is going to return the number of such indices. So the subexpression is counting the number of places that LOGICAL is true. One way of counting the places that are true is nnz(), so your code can be replaced with
a(z) = nnz(magnew >= zz(z) & magnew < zz(z+1)) / length(magnew)
But you can go further to make it more compact. Since you are dividing by the number of items, you are effectively calculating the fraction of the entries that are true. But the fraction that is true is the same as the mean:
a(z) = mean(magnew >= zz(z) & magnew < zz(z+1));
You can also do better still. In the case where the entries in z are sorted, your loop can be replaced by
counts = histc(magnew, zz);
a = counts(1:end-1)./length(magnew);
The reason you take counts(1:end-1) is that for histc, the last entry that is returned would be the count of the values that are exactly equal to zz(end) which is something that your loop does not calculate. Your other entries are counting the number of entries that are >= a(i) and strictly less than a(i+1), which is exactly what histc() does except for the last entry.
Note: the new histcounts() is not an exact substitute for histc() in this regard. histcounts() has the property of testing a(i) <= x < a(i+1) except for the last entry, for which the test is a(end-1) <= x <= a(end) which is not what your loop calculates.