Pregunta

Suppose you had a global variable G in a function f, say. The output of f is dependent on G, and G is declared to be global within f.

I would like f to work as follows through the command window:

  • set G to some value
  • run f, giving some result dependent on G
  • set a different value of G
  • run f again, giving an answer dependent on the new G

However, this has the following problem: it would involve defining G first, then declaring it to be global when f is run, which results in a matlab warning I would also require that the global variable G is not a direct input for f.

Any help to work around this, or if my method is fundamentally flawed, an alternative would be greatly appreciated.

¿Fue útil?

Solución

Yes you can do this. A simple example:

In the command window, enter global G and G=2.

Then make a simple function, e.g.:

function incG
global G
G=G*2;
disp(G)

Run incG from the command window and see what happens. You can also modify the value of G in the command window in between executing incG. You do have to be careful that G exists and has the correct value when you run incG.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top