Reputation: 9708
I have a strange error: the first time I run the code listed below I get this nice plot
The code:
%% Area under the curve
subplot(1,2,1);
r = 1;
i_start = runi(r,1);
i_end = runi(r,2);
x = D(i_start:i_end,c);
y = F(i_start:i_end,c);
plot(x,y);
subplot(1,2,2);
area(x,y);
area = polyarea(x,y);
text(0.5,200, ['area:' num2str(area)])
maxD = max(D(i_start:i_end,c));
text(1.0,290, [num2str(maxD) 'mm']);
arrow([maxD/2,250],[maxD,250]);
When I then run the same code again without changing anything I get this error
Subscript indices must either be real positive integers or logicals.
When I run through the code line by line I see that the error occurs because of area(x,y)
but I really do not understand what the problem is.
whos x y
Name Size Bytes Class Attributes
x 496x1 3968 double
y 496x1 3968 double
Any help, please?
Upvotes: 1
Views: 284
Reputation: 47402
It's because you've assigned the name area
to an array, in the line
area = polyarea(x,y);
Now the line
area(x,y);
is interpreted as "get the values of the matrix area
at the indexes given by x
and y
". But subscript indices have to be integers or logical values, whereas x
and y
are floating points.
Here are some possible solutions:
Put the line clear all
at the top of your script, which will clear all variable assignments (however, if you overwrite a built-in function in one line of a script and then try to call it in a later line, you will get the same issue). This also has the drawback that you lose your workspace every time you run the script, which may not be desirable.
Rewrite your script as a function. This gives it its own local scope, so that you can't overwrite variables in the global workspace. If you need to access variables in the global workspace, you can either declare them as global
(dangerous) or pass them in as arguments to the function (better). If you need to be able to modify arguments in the workspace, pass them back as outputs from the function and overwrite them explicitly. This is my preferred solution - in fact I never use scripts, only functions.
Don't ever overwrite built-in functions! This should be a habit.
A good way to ensure that you don't override built-ins is to use a text editor that colors words according to their function. For example, this is how your code looks in my text editor (Sublime Text 2):
In line 12, it's obvious that I'm overwriting a built-in function. After a while, you learn to feel really uncomfortable when you see red text on the left of an assignment operator! If I change the name of that variable, I see this instead:
which makes me feel much happier.
Upvotes: 2