Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share a variable between two functions in MATLAB?

Tags:

matlab

I have two functions in matlab, which roughly look like this

function f1()
  setup_callback(@f2);
  a = 1;
  evaluate_callback();
end

function f2()
  ...
end

where evaluate_callback is an external library function which calls f2.

I want to be able to read the current value of a from inside f2. Is there some way to achieve this without using globals?

like image 465
Benno Avatar asked Jun 06 '12 16:06

Benno


2 Answers

Make f2 a nested function inside f1:

function f1()
    setup_callback(@f2);
    a = 1;
    evaluate_callback();

    function f2()
      %# you can access a here
      disp(a)
    end
end
like image 55
Amro Avatar answered Sep 28 '22 07:09

Amro


Nested functions will provide the scoping you want. Note that there's no other way to call the f2 callback function than either from inside f1, or via the function handle. So f1 could return the @f2 handle, and other functions at global scope could call it that way.

function f1()
  setup_callback(@f2);
  a = 1;
  evaluate_callback();

  function f2()
    % refer to a
    ...
  end
end
like image 26
Peter Avatar answered Sep 28 '22 09:09

Peter