MATLAB Answers

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

6 views (last 30 days)
JP
JP on 23 Nov 2019
Commented: Jan on 23 Nov 2019
Hello,
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)
patch(get(h(p),'XData'),get(h(p),'YData'),cmap(5-p,:),'FaceAlpha',.5);
eval(['meanLocal = mean_',stain,'_',orien,'_',magn,'_',comp,'(p,1)'])
plot(p,meanLocal,'x','MarkerSize',15,'MarkerEdgeColor',cmap(p,:),'MarkerFaceColor',cmap(p,:),'LineWidth',2)
end
After a few iterations I get the following error:
Error using matlab.graphics.primitive.Line/get
Invalid or deleted object.
Error in boxplotting2 (line 77)
patch(get(h(p),'XData'),get(h(p),'YData'),cmap(5-p,:),'FaceAlpha',.5);
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.

  0 Comments

Sign in to comment.

Answers (1)

Jan
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

  2 Comments

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',...
cmap(p,:),'MarkerFaceColor',cmap(p,:),'LineWidth',2)
end
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
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