help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Need help setting a flag once in sub.m when called from main.m


From: Jaroslav Hajek
Subject: Re: Need help setting a flag once in sub.m when called from main.m
Date: Tue, 9 Mar 2010 12:05:53 +0100

On Tue, Mar 9, 2010 at 11:52 AM, Svante Signell
<address@hidden> wrote:
> On Tue, 2010-03-09 at 10:06 +0100, Jaroslav Hajek wrote:
>> On Tue, Mar 9, 2010 at 9:29 AM, Svante Signell <address@hidden> wrote:
>> > Hi,
>> >
>> > I have the following problem:
>> >
>> > I need to call a subfunction once from the main function, setting a flag
>> > that it has been called. This should work as long as the workspace is
>> > not cleared. I can solve it by a persistent variable in the subfunction
>> > but it is not a nice solution.
>> >
>> > Code below:
>> >
>> > main.m:
>> > <how to declare status here?>
>> > status = sub(status);
>> > or
>> > status = sub();
>> >
>>
>> persistent status = sub ();
>
> Sorry, setting persistent in the calling script does not work. From my
>  understanding it can  only be used in a function.
>

You wrote "from the main function", not "main script".

> octave test_sub1.m
> warning: ignoring persistent declaration near line 5 of file
> `test_sub1.m'
>
> Working code:
> ==============
> % File: test_sub.m
> status = "";
> printf("Before calling sub\n");
> status = sub()
> printf("After calling sub\n");
>
> % File: sub.m
> function status = sub ();
> persistent called;
> if (strcmp (called,'y') == 0)
>  fprintf ('sub: Entering here once\n');
>  called = 'y';
>  status = 'yes';
> else
>  status = 'no';
> end%if
>
> Not working code:
> =================
> % File: test_sub1.m
> status = "";
> printf("Before calling sub1\n");
> persistent status = sub()
> printf("After calling sub1\n");
>
> % File: sub1.m
> function status = sub1 ();
> if (strcmp (status,'yes') == 0)
>  fprintf ('sub1.m: Entering here once\n');
>  status = 'yes';
> end%if
>
> The question was how to avoid the persistent variable in sub.m?
>
>

Persistent variables are the nice way to do this. If you want to avoid
the explicit checking, you can do (this is in fact what I suggested
before);

sub.m:
function status = sub ()
persistent status = sub1 ();
endfunction
function status = sub1 ()
printf ('sub1.m: Entering here once\n');
status = 'yes';
endfunction

If you want something really hacky-wacky,

function status = sub ()
printf ('sub.m: Entering here once\n');
status = 'yes';
assignin ("caller", "sub", status);
endfunction

but don't let this code anywhere near me :)

-- 
RNDr. Jaroslav Hajek, PhD
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz



reply via email to

[Prev in Thread] Current Thread [Next in Thread]