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.
Add to your example the counter as output and you will see the increments:
And the example:
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