Why do I get an 'Index needs to be positive or logical' error?

1 view (last 30 days)
I'm attempting to take values in space and if they fall within a predetermined circle to change the value of that point in a blank matrix to one with zeros elsewhere.
After the first x,y plane is checked for points falling within the circle, the for loop index's to the next 'z' point and reexamines the x,y plane at this new value of z to see what points of the xy plane fall within the circle (that has expanded due to it being a cross section of a cone).
When I attempt to run it, I get the error that B(1,15,1) cannot be accessed as the index needs to be real or logical yet 1,15 and 1 are all logical and the for loop has managed to index up to 15 in the y dimension. Any suggestions?
Here is my FOR loop;
B=zeros(50,50,length(Z));
for z=1:length(Z)
c=(z*tan(15))^2;
for x=1:0.1:5
for y=1:0.1:5
if c>(x-x_0)^2+(y-y_0)^2
i=(10*x)-9
j=(10*y)-9
B(i,j,z)=1;
else
i=(10*x)-9
j=(10*y)-9
B(i,j,z)=0;
end
end
end
I use 'i' and 'j' to remove the fact x and y are indexing in 0.1 increments, x_0,y_0 and z_0 are the location of the apex of the cone and falls at (25,25,0). It is probably not the most efficient way of doing this.

Accepted Answer

Amit
Amit on 2 Feb 2014
Sometimes in matlab, when doing floating point operations which should result in an integer, deviate from it slightly. For example, getting 1.00000000001 instead of 1. When you try to use this in indexing, you might get an error, as the first number is very close to 1, but is not 1.
You can do something like this:
i = round((10*x)-9);
j = round((10*y)-9);

More Answers (0)

Community Treasure Hunt

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

Start Hunting!