passing by reference an object in a function
显示 更早的评论
I have a simple question about passing a variable by reference in Matlab. from the forums I have seen, there is no clear answer about that. From what I have understood( but may be I am wrong), let say that you have a function that take a table A and want to change in this table only the h line. if I do
function arg=myFunction(A,h)
A(h,:) = A(h,:)+2;
end
and call myFunction(A,3), A will not be changed. When specifying myFunction like this
function A=myFunction(A,h)
A(h,:) = A(h,:)+2;
end
and calling myFunction(A,3), A is changed. But from what I understood of what matlab does, matlab is copying A, then change in the copy the h lines of A, then provide output the copy. First question: Is this true or not? and if yes, is there a way to pass it by reference, which means directly modifying A. I know that by doing directly A(h,:) = A(h,:)+2; in the command line, I can obtain the same result. but on some applications, when A is very large, like Gibbs sampler, where i want to sample sequentially each line of A conditionnally to the other ones, it looks to me that copying for every call the large dataset A is inefficient. I am not an expert of matlab, please excuse if the question is stupid.
1 个评论
Adam
2015-6-9
In general in Matlab everything is copied by value, yes. The link James gives below should be sufficient for your needs I think.
The other approach which is what I always use is to use Object-oriented programming.
Classes that are derived from the handle class are always passed by reference.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!