Elliot Lee - 18 days ago 7

R Question

I am learning to program in MATLAB, and have some experience in R. I am confused by the nature of scope in MATLAB.

`y <- 1`

test <- function(x) {

return(x+y)

}

test(1)

in R, this returns a value of 2. R checks outside of the function for a value of y, when y is not passed as an input. However, in MATLAB,

`function[ output ] = test(x)`

output=x+y;

y=1;

test(1)

gives the error

`Undefined function or variable 'y'`

Can anyone explain the logic behind why scope behaves differently in MATLAB than I, a programmer in R, would expect it to work?

Answer

In matlab you have specify if the variable is `global`

. You can do something like this:

```
function[ output ] = test(x)
global y;
output=x+y;
end
```

and then call the function:

```
global y;
y = 1;
test(1)
```

As far as I know this is not very common way of doing things in Matlab and Iwould advice against it. Instead you should just pass all variable to the function.

```
function[ output ] = test(x,y)
output=x+y;
end
```

and then call the function:

```
y = 1;
test(1,y)
```

Source (Stackoverflow)

Comments