Possible to create a function where the input is changed?
6 次查看(过去 30 天)
显示 更早的评论
I understand it is one of the "cardinal rules" of MATLAB that functions do not affect the input values (versus scripts that do); however, is it possible to create a function where this is violated?
For example:
>>x = 10
>>Function(x)
%Running this would change the value of x in the workspace to some other value
0 个评论
采纳的回答
更多回答(2 个)
Matt Tearle
2012-2-10
I am not doing this...
classdef passbyref < handle
properties
value
end
methods
function x = passbyref(y)
x.value = y;
end
function notagreatidea(x)
x.value = x.value + 1;
end
end
end
And then
>> x = passbyref(42)
>> notagreatidea(x)
>> x
May Cleve have mercy on my soul.
Also: what Sean and Walter said.
7 个评论
Matt Tearle
2012-2-10
I'll let you argue the semantics with your bet opponent, but notagreatidea is kindasorta a function -- it's actually a method of the passbyref class. So it only works on passbyref objects. However, once you have a passbyref object (x = passbyref(42)), it is a single "function call" that invokes the notagreatidea method and changes its value property.
For the sake of your bet, follow Sean's first link... [hint]
Walter Roberson
2012-2-10
Yes, it is possible. There are not many cases where it is a good idea, however.
0 个评论
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!