help-octave
[Top][All Lists]
Advanced

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

Re: Retained Value


From: Thomas D. Dean
Subject: Re: Retained Value
Date: Wed, 13 Jul 2016 10:26:32 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.8.0

On 07/13/2016 09:19 AM, Przemek Klosowski wrote:
On 07/13/2016 11:44 AM, Thomas D. Dean wrote:
I have some code, that unless I clear all, does not change value when
changed.

X=[0,38000]
Y=[0,3000]
poly_deg = 4
global P = polyfit(X,Y,poly_deg)
P

X=[0,38000]
Y=[0,3000]
poly_deg = 8
global P = polyfit(X,Y,poly_deg)
P

P has the same value as before.

What am I doing wrong?
Well, you are fitting polynomials of fourth and eight degree to two
points---no good can come out of that.
But your problem has nothing to do with the poly* math: it's just that
globals are weird:

P
   undefined

global P=1

P
   1

global P=2

P
    1                                   That's strange---the value
didn't change...

clear P

P
   undefined                        OK, we got rid of P.......

global P=2

P
   1                                   .....  except that somehow
previous value was retained.

Wha?????

I think the explanation is that 'global' is a statement about the
variable, and the assignment to this variable should be a separate
statement. Apparently  multiple in-line assignments don't work that
well. If you write it as

global P
P=1
P=2

it works as expected.

By the way, global only matters when you want some variables to be
available within functions, so the usage pattern is

global P
function fun(); global P; ... P... ; end

and it has to be said that the concept of global is a crutch, and should
be avoided if possible.
I simplified the problem to something small that still showed my mis-understanding of what I was doing! I have a large script file I used for 'proof of principle' so it was very messy. I changed most of this file into a function file that works better.

I now use persistent inside a function. This is better than global, as I believe, it makes better code. The function is defined as

  function [r] = xx(v, newP=[])
    persistent P = [];
    if ( numel(newP) > 0 )
        P = polyder(newP);
    endif
    r = polyval(P,v);
  endfunction;

Tom Dean



reply via email to

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