How to pass matrix by reference or get the return value of function

自闭症网瘾萝莉.ら 提交于 2019-12-29 09:22:49

问题


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


回答1:


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.




回答2:


The output of the function recursive_remove hasn't been defined and so you ouput can't be used anywhere else.

In matlab you define outputs of functions with square brackets as below.

function [ output1, output2 ] = recursive_remove( input1, input2 )

The outputs can now be passed into other MATLAB docs - functions.

When calling the function in the example above in a different function as you did in your first bit of code you would call it as shown:

current_loads = zeros(1, 118); 
for col=1:118
    current_loads(1,col)=10; %Initially give all nodes a current load of 10    
end
[ output1, output2 ] = recursive_remove( input1, input2 ); %calling function

With this syntax you can take output1 and call it in the input of your next function recursive_remover



来源:https://stackoverflow.com/questions/29902159/how-to-pass-matrix-by-reference-or-get-the-return-value-of-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!