Possible to create a function where the input is changed?

6 visualizaciones (últimos 30 días)
Josh
Josh el 10 de Feb. de 2012
Editada: Erik el 8 de Oct. de 2013
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

Respuesta aceptada

Sean de Wolski
Sean de Wolski el 10 de Feb. de 2012
doc assignin
doc evalin
Why would you want to do this?
  6 comentarios
Josh
Josh el 10 de Feb. de 2012
It was more a bet of whether or not you can or cannot do it. I'll be sure to try and figure it out using that documentation; worst case scenario I'll use Matt's idea.
Josh
Josh el 13 de Feb. de 2012
Was able to create a function to do just this using assignin, thank you!

Iniciar sesión para comentar.

Más respuestas (2)

Matt Tearle
Matt Tearle el 10 de Feb. de 2012
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 comentarios
Matt Tearle
Matt Tearle el 10 de Feb. de 2012
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]
Josh
Josh el 13 de Feb. de 2012
Thanks for the help, but went with Sean's answer for simplicity's sake.

Iniciar sesión para comentar.


Walter Roberson
Walter Roberson el 10 de Feb. de 2012
Yes, it is possible. There are not many cases where it is a good idea, however.

Categorías

Más información sobre Tables en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by