How to pass a matrix by reference or get the return value of a function
I have a 1 x 118 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, 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 the function call recursive_remove
(see below).
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 I do with this matrix current_load
from this function, it will not update as I don't know how to pass it by reference.
I am new to Matlab. I would really appreciate if you could show an example on how to handle this
source to share
EDIT: "How to pass a parameter by reference in Matlab" You can solve your problem by passing your arguments by reference
You need a class
Class handling
Objects that exchange references with other objects
this, create a file named 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 this you can get some kind of link pass and avoid getting a lot of copies caused by your program.
source to share
The output of the recursive_remove function is undefined and therefore you cannot use it elsewhere.
In Matlab, you define the outputs of functions with square brackets as shown below.
function [ output1, output2 ] = recursive_remove( input1, input2 )
Outputs can now be passed to other MATLAB Docs functions .
When you call the function in the above example in another function, as you did in the first bit of code, you 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 the following functionrecursive_remover
source to share