help-octave
[Top][All Lists]
Advanced

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

Modifying global variables from within functions


From: Roberto Hernandez
Subject: Modifying global variables from within functions
Date: Tue, 13 Nov 2001 17:26:28 -0300
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.5) Gecko/20011012

Hello everyone,

I am trying to modify a global variable directly from within a function. The solution I found is somewhat complicated for what I want. I was wondering if there's a better way to do it.

Here's the situation. The function "foo" has to accept a global variable name and a value and assign the value to the variable.

For example this function:

------------------------------
function foo(varName, newValue)
    eval(["global ",  varName]);

    if isnumeric(newValue)
        eval([varName, " = " , num2str(newValue), ";"])
    else
        eval([varName, " = \"" , newValue, "\";"])
    endif
endfunction
------------------------------

So I would call it this way:

------------------------------
octave:1> global a
octave:2> foo("a", 5)
ans = 5
octave:3> foo("a", "hello")
ans = hello
------------------------------

The previous example works fine. But if I want to do more complex operations inside the function "foo", then having to use "eval" and building lots of strings becomes annoying. It's easy to make mistakes and pretty bad for debugging.

The question is: Is there a better way to do this?

TIA,

-Roberto



-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.octave.org
How to fund new projects:  http://www.octave.org/funding.html
Subscription information:  http://www.octave.org/archive.html
-------------------------------------------------------------



reply via email to

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