MATLAB Answers

Why is my code showing an error? Why is the line deleted?

11 views (last 30 days)
JP on 23 Nov 2019
Commented: Jan on 23 Nov 2019
This is my code to fill out boxplots and to visualize the mean value as a cross 'x'.
h = findobj(gca,'Tag','Box');
for p=1:length(h)
eval(['meanLocal = mean_',stain,'_',orien,'_',magn,'_',comp,'(p,1)'])
After a few iterations I get the following error:
Error using
Invalid or deleted object.
Error in boxplotting2 (line 77)
I can't seem to figure out why h(p) is a handle to a deleted line. There is nothing in my code that could delete the content.
It would be greatly appreciated if someone could help me with this issue.


Sign in to comment.

Answers (1)

Jan on 23 Nov 2019
The shown code does not reproduce the problem. We cannot guess reliably, why one of the obejcts in h is deleted. But a weak guess:
plot is a hight level command, which clears the current axes object before inserting a new element - except if you have called hold('on') before or set the 'NextPlot' property to 'add'.
The eval command is a really bad design. See TUTORIAL: how and why to avoid EVAL


Image Analyst
Image Analyst on 23 Nov 2019
Jan is exactly right. You get the handles to everything in h before the loop, but because you didn't call hold on before the first call to plot(), that first call to plot() blows away everything in the plot, which means h is now holding a bunch of handles to no-longer-existing axes objects. To fix it, call "hold on" before the first plot. That will prevent plot() from blowing away your existing axes objects. It will just add new ones.
h = findobj(gca,'Tag','Box');
hold on; % Prevent objects from being blown away by plot().
for p = 1 :l ength(h)
patch(get(h(p), 'XData'), get(h(p), 'YData'), cmap(5-p,:), 'FaceAlpha', .5);
fprintf('meanLocal = mean_%f_%f_%f_%f(p, 1)\n',stain,orien,magn,comp);
plot(p, meanLocal,'x','MarkerSize',15,'MarkerEdgeColor',...
Also note how I use fprintf() instead of the hated eval(). It assumes that those variables are doubles. If they are integers use %d, if they are strings use %s.
Jan on 23 Nov 2019
@Image Analyst: With fprintf the value of meanLocal is not adjusted. Unfortunately the eval() is really needed, because the OP has stored the variables with encodeing the parameters in the name of the variable:
meanLocal = mean_STAIN_ORIEN_MAGN_COMP(p,1)
% where the uppercase parts are variable

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by