MATLAB Answers


How do I use IF-loops with plot_handles?

Asked by fxo
on 20 May 2013

I'm having a bit of a problem to integrate the if-loop with plot handles. So the program I'm writing has this structure:

It has this menufile in which you choose what you want to do (This is only a small part of it):

    case 1
    plot_handles = createPlot(plot_handles);
    case 2

In case 1 you'll be able to index a figure and write the function which is plotted and you're being returned to the menu.

    function plot_handles = createPlot(plot_handles)
    figureid = input('Input figure-ID: ');
    func= input('Input function f(x): ','s');
    error('Nonvalid function!');

Back in the menu I enter case 2 where the thought is that it'll ask you which figure you want to edit.Once you've choosen that you're supposed to be able to edit that figures' linewidth:

    function changeWidth(plot_handles)
    figureid = input('Input figure-ID: ');
    h = plot_handles(figureid);
    if exist(figureid)== 0 % Here's the problem, I don't know how to test if ...
    % the ID is correct or not.
        error('Invalid figure-ID')
    width=input('Input new width: ');
    set(h, 'linewidth', width) 

The problem is that I don't know how to check if figure-ID is correct in the IF-loop, elsewhere I want the errormessage so be written out.

Would really appreciate some help!


1 Answer

Answer by per isakson
on 20 May 2013
Edited by per isakson
on 20 May 2013
 Accepted answer

"check if figure-ID is correct "

There is a function:

    Test for valid graphics object handle


I think code cells are useful when experimenting with code, see Evaluate Subsections of Files Using Code Cells. One small step at a time, check the result and proceed to next step.

Doc says:

    h = ezplot(...) returns the handle to all the plot objects in h.

My first step:

    h = ezplot( @sin );
    get( h, 'Type' )


    ans =

Thus, ezplot returned the handle of the line object. Did you expect that?


on 20 May 2013

Thank you for the quick answer!

Could you possibly help me a bit more, am I on the right way if I write it like this?

if ishandle(plot_handles(figureid))
Set_Title=input('New Title: ','s');
h = plot_handles(figureid);
title( Set_Title,'FontSize',16)
error('Invalid figure-ID')
on 20 May 2013

I solved it on my own using ishandle as you said, once again, thank you for the waypointer!

"right way" that depends on who you ask. I doubbt.

  • I hessitate to use the same variable, h, as handle to a graphic object and index to a double array.
  • I hessitate to rely on current figure and current axes when more than one figure or axes exist simultaneously.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!