How to pass a parameter by reference in Matlab

I am new to Matlab and am learning about the following question online and am having difficulty solving it. I have a 1 x 20 matrix called current_load

which I have to update periodically. This matrix is ​​in the main Matlab workspace (as shown below in the code).

current_loads = zeros(1, 20); 
for col=1:20
    current_loads(1,col)=10; %// Initially give all nodes a current value of 10    
end

Object = HandleObject(current_load);%To pass by reference
recursive_remove(Object, 0);

      

To pass current_load

by reference, I created the following HandleObject.m class

classdef HandleObject < handle
   properties
      Object=[];
   end

   methods
      function obj=HandleObject(receivedObject)
         obj.Object=receivedObject;
      end
   end
end

      

This matrix will be passed to the function call recursive_remove

(see below).

function recursive_remove( current_load, val )
     current_load.object = new matrix;
     if(val<10)
        current_load.object(1,3) = 2+val; %Not the correct way of using current_load ??
     end
     recursive_remove( current_load, current_load.object (1,3) )
end

      

The intent here is to change the variable current_load

in this function and later I can see these same changes from the main one. But this code doesn't work as I don't know how to follow the link. I need to traverse the link since I am calling this recursively without going back to the main one to force it to overwrite its variable in the caller. Please provide an example if possible.

+3


source to share


1 answer


If you really need this feature, you can take a look at turning your HandleObject class into a singleton like this:

classdef HandleObject < handle
   properties
      Object=[];
   end
    methods(Static)
    function obj = Instance(receivedObject)
        persistent uniqueInstance

        try
            if isempty(uniqueInstance)
                obj = HandleObject(receivedObject);
                uniqueInstance = obj;
            else
                obj = uniqueInstance;
            end
        catch ME
            disp(ME.getReport);
        end
    end
   end
   methods
      function obj=HandleObject(receivedObject)
         obj.Object=receivedObject;
      end
   end
end

      

Your recursive function will get a little simpler:

function recursive_remove(val )
   current_load = HandleObject.Instance();
   current_load.object = new matrix;
   if(val<10)
       current_load.object(1,3) = 2+val;
   end
   recursive_remove(current_load.object (1,3) )
end

      



And to instantiate the HandleObject class do the following:

Object = HandleObject.Instance(current_load);

      

Hope this helps you further.

0


source







All Articles