0

I'm facing a question about using matlab to change a given variable inside a function & return it. This function should change the value w/o create any new var

according to the description, I suppose it is something like:

vec = [1, 2, 3, 4, 5];
func(vec);
vec
   1, 3, 5

after googling a lot, I've read a lot about that matlab is passing the reference rather than value. Thus the input parameter will be modified, and what I have to do is simply return it. NO luck...

Here is my code:

function x = func(x)
    x = x(mod(x, 2) == 1)
end

can anyone tell me why this is not working??

Sanagi
  • 31
  • 2
  • Looks fine to me. Were you perhaps expecting `vec` to be replaced? – beaker Mar 11 '16 at 00:45
  • 1
    TL;DR: you need to assign the output (cf. dup suggestion). It's not working because Matlab's copy-on-write is not the same as pass-by-reference. It is true that if the input variable is not altered, Matlab will not make a copy of it or if the JIT thinks it can, it will perform in-place updating. However, you cannot directly update the state of a simple variable via either of these mechanisms; that requires a `classdef` or a closure which possess their workspace in memory. – TroyHaskin Mar 11 '16 at 00:49
  • Thanks, the answer is very clear. – Sanagi Mar 11 '16 at 10:02

0 Answers0