help-octave
[Top][All Lists]
Advanced

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

Re: Retained Value


From: Przemek Klosowski
Subject: Re: Retained Value
Date: Wed, 13 Jul 2016 12:19:30 -0400
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.1.1

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.


reply via email to

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