Can you perform a delayed set (:= in Mathematica) in Matlab?

后端 未结 2 1104
温柔的废话
温柔的废话 2020-12-20 22:17

So, I\'ve recently converted from Mathematica to Matlab, and while Matlab has most of Mathematica\'s useful features, I can\'t figure out how to perform the equivalent of Ma

2条回答
  •  [愿得一人]
    2020-12-20 23:02

    Actually your proposed solution doesn't work as expected:

    y = 2;
    x = @()(y);
    y = 3;
    x()
    

    when you define the anonymous function, it create a closure and captures/copies the value of y at that moment (now it has its own copy of y). Then if you change the y on the outside, it would not affect the one created in the closure, thus in your example the last value would return 2 not 3

    The only way I can think of is to encapsulate the variable in a closure and expose set/get methods (just like in OOP)

    IMO, MATLAB and Mathematica have two very different languages, thus I would embrace the MATLAB-way and not try emulate features of other languages (that is usually not the best thing to do)

提交回复
热议问题