0

I am trying to modify a structure array from within a nested function, where the nested function is 'returned' through a function handle. From what I know, you cannot modify the structure array from the 'outer' function, since MATLAB pass arguments by values and not by references. However, you should be able to do it from within a nested function as the nested function can access the 'parent' scope. However when I 'address' the function using function handle it does not work.

Here is the code:

function object = objectReader()
   object.counter = 0;
   object.getData = @GetData;

   function data = GetData(input)
      object.counter = object.counter+1;
      data = input*1.23456789;
   end

end

From what I found, it could be that when making the function handle, it also makes a copy of the 'current' scope so the function since than lives in 'isolated environment'.

So the question is, how can I do modify a structure array from within a nested function, while maintaining the outside interface? By outside interface I mean that you can do:

object = objectReader();
data = object.getData(1);

and object.counter increments each time you call object.getData() function.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
rad
  • 157
  • 1
  • 9
  • This is weird and convoluted. You are trying to create an object with a method. Use `classdef` for that. Closures are not intended for this. – Cris Luengo Aug 10 '20 at 13:58

1 Answers1

0

Add to your example the counter as output and you will see the increments:

function object = objectReader()
   object.counter = 0;
   object.getData = @GetData;

   function data = GetData(input)
      object.counter = object.counter+1;
      data = [input*10 ,object.counter];
   end
end

And the example:

myobject = objectReader();
disp(myobject.getData(1)); % 10     1
disp(myobject.getData(1)); % 10     2

Read more about closure here: https://research.wmz.ninja/articles/2017/05/closures-in-matlab.html

And it is more natural to do it using class with properties and methods: https://uk.mathworks.com/help/matlab/matlab_oop/create-a-simple-class.html

Mendi Barel
  • 3,350
  • 1
  • 23
  • 24
  • This solution however does not work as excepted, since the idea was to increment `myobject.counter`. However learning more about closures I was able to change the logic so it is no more needed. – rad Aug 11 '20 at 09:54