How does MATLAB function pass input argument into the function?

I have a class with properties in it (let say the name of the class file is inputvar), and I use it as the input argument for two different functions, which have an exactly the same calculation, but a little bit different code, which I'll explain later.
For the first function (let say the name is myfun1), I wrote the input argument like this: f = myfun1 (inputvar). So every time I want to use variables from the class inside the function, I'll have to call inputvar.var1, inputvar.var2, and etc.
For the second function (myfun2), I wrote each variables from the class in the input argument, so it looks like this: f = myfun2 (inputvar.var1, inputvar.var2, ... etc ). So inside the function, I just have to use var1, var2, and etc, without having to include the name of the class.
After running both functions, I found that myfun2 runs about 50% faster than myfun1 (I used tic-toc). Can someone explain to me exactly why is that?

답변 (1개)

Sean de Wolski
Sean de Wolski 2013년 7월 26일

0 개 추천

How many times did you run this to get your timing? Run it at least 10x in a for loop to get a convincing timing metric.
I would expect it to be comparable in terms of time as both are passing by reference.

댓글 수: 2

Hey thanks for replying, Sean!
They run for more than 1000 times, and I have redone it several times, so I'm pretty sure that's a correct timing metric.
My thinking is instead of letting the function to locate the variables in the class by itself (this is what happens in myfun1), it would be faster to tell the function exactly which variables to be used (like in myfun2). Does that make sense? But I just don't know how to test that, and if that's a right explanation at all. I don't really understand how does MATLAB function pass by reference though.
Cedric
Cedric 2013년 7월 26일
편집: Cedric 2013년 7월 26일
I also observed timing differences in this context, with a little difference in the setup.
Passing obj to a method, I timed accessing many times e.g. obj.x within the method in various computations, as well as creating a local copy and working with the copy, e.g.
x_ = obj.x ;
% .. work on x ..
obj.x = x_ ;
and the latter was consistently more efficient.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Performance and Memory에 대해 자세히 알아보기

질문:

2013년 7월 26일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by