Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a 1 x 118 matrix called current_load that I need to update periodically. This matrix resides in the main workspace of Matlab (as shown in the code bellow).

current_loads = zeros(1, 118); 
for col=1:118
    current_loads(1,col)=10; %// Initially give all nodes a current load of 10    
end
recursive_remove(current_loads); %calling function

This matrix will be passed to a function call recursive_remove (shown bellow).

function updater = recursive_remove( current_load )
     current_load(1,3) = 2.6; %// This update can't be seen from main ??
     %this function will be called recursively later
end

But whatever updates I do to this current_load matrix from the function, it will not get updated since I don't know how to pass it by reference.

I am new to Matlab. I would greatly appreciate if you can show with an example how to handle this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
845 views
Welcome To Ask or Share your Answers For Others

1 Answer

EDIT: "How to pass parameter by reference in Matlab" You can solve your problem passing your arguments by reference

You need a handle class

Handle Classes

Objects that share references with other objects

this is, create a file called HandleObject.m with this code:

classdef HandleObject < handle
   properties
      Object=[];
   end

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

Then you can do something like this

Object = HandleObject(your matrix)
yourFunction(Object)

And inside your function

function yourFunction(myObject)
    myObject.object = new matrix;
end

With that you can achieve some kind of pass by reference and avoid getting a lot of copies trought your program.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...