How to detect if a plot has already existed?

What I want to do is to plot my sampling stations on a map. The map is pre-plotted . I want to delete the previous sampling stations (h1 handle) if they already exist and then plot the new sampling stations.
Below is my code:
if isexist(h1)
delete(h1);
end
hold(app.mapPlot, 'on');
h1 = plot(app.mapPlot, lonlat(:,1), lonlat(:,2), 'o', 'color', 'b','markersize', 5);
Unfortunately, I got the below error:
Unrecognized function or variable 'h1'
Any idea on how to make this work?

 채택된 답변

Joe Vinciguerra
Joe Vinciguerra 2019년 10월 23일

0 개 추천

Try this... (note I'm using "exist" instead of "isexist")
clear % I'm starting with no 'h1'. This checks the "False" condition
if exist('h1')
delete(h1); % if 'h1' is a thing, delete it
end
h1=plot([5 8],[12 11]); % now there is an 'h1' either way
hold on; % I insertered this to match your application
pause(3); % wait a few seconds to verify it visually
% Let's do it again to check the "True" condition
if exist('h1')
delete(h1); % if 'h1' is a thing, delete it
end
h1 = plot([1 2],[2 4]); % still works

댓글 수: 3

Leon
Leon 2019년 10월 23일
편집: Leon 2019년 10월 23일
Many thanks! It works for your example. Weird enough, when I plug the code in my app-Designer script, it does not work (there is no error message anymore, but the lonlat stations are just not deleted).
if exist('h1')
delete(h1);
end
if exist('h2')
delete(h2);
end
hold(app.mapPlot, 'on');
h1 = plot(app.mapPlot, lonlat(:,1), lonlat(:,2), 'o', 'color', 'b','markersize', 5);
lonlat2 = [];
for i = min(b1,b2):max(b1,b2);
if Sta{i}.lon>=20
lon = Sta{i}.lon;
else
lon = Sta{i}.lon+360;
end
lonlat2 = [lonlat2; lon, Sta{i}.lat];
end
h2 = plot(app.mapPlot, lonlat2(:,1), lonlat2(:,2), 'ro', 'markerFaceColor', 'r', 'markersize', 5);
hold(app.mapPlot, 'off');
I'm not as familiar with the app designer, but I'll try to help.
Are you sure it's really not deleting? Or is it deleting and replotting the same data quick enough that you don't notice?
Try another command instead of "delete". Perhaps "close"?
Many thanks! Weird enough, if I put the below code after the plot, it will delete the current sampling stations as expected. However, if I move it ahead of the plotting routine, the previously plotted sampling stations will remain there.
if exist("hh1")
delete(hh1);
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

릴리스

R2019b

질문:

2019년 10월 23일

댓글:

2019년 10월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by