Passing Matrix using call by reference
Mostrar comentarios más antiguos
When looking for call-by-reference in matlab I found the Handle-Class. What I don't yet understand is how I use that class on a matrix so that I can pass a reference of the matrix and not the matrix itself.
I know matlab already kind of does this with large matrices, but firstly, I don't know how big my matrices will become, and secondly, I want to make sure it is only with reference, since it is done very often and is a performance critical operation.
Thank you.
Respuesta aceptada
Más respuestas (4)
Jos (10584)
el 10 de Dic. de 2013
Yes, using assignin and input name will do that for you
function myfun(varargin)
assignin('caller',inputname(1),2)
>> test = 'hallo'
test =
hallo
>> myfun(test)
>> test
test =
2
1 comentario
Daniel
el 10 de Dic. de 2013
Sean de Wolski
el 10 de Dic. de 2013
Editada: Sean de Wolski
el 10 de Dic. de 2013
What operation are you doing inside of myfunc? Is it elementwise?
If so, MATLAB will do the operation in place if x is named the same everywhere:
x = magic(10);
x = myfunc(x);
%%
function x = myfunc(x)
x = x.^2;
end
Since the operation is being done in-place, no memory copy will be necessary.
1 comentario
Daniel
el 10 de Dic. de 2013
Jos (10584)
el 10 de Dic. de 2013
Matlab does not create a copy, until it is really needed. So passing big arrays to functions uses no extra memory, except when you change the big matrix inside the function.
function myfun1(X)
Y = X ; No copy is made, Y is a pointer (a reference to X)
X(1) = 1 % this creates a copy of X inside the workspace of the function. Note that Y is untouched.
Y(1) = 1 ; % this now also creates a copy
2 comentarios
Daniel
el 10 de Dic. de 2013
Editada: Sean de Wolski
el 10 de Dic. de 2013
Jos (10584)
el 10 de Dic. de 2013
Editada: Jos (10584)
el 10 de Dic. de 2013
OK. Yes, it is possible. See my second answer.
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!