Elliot Lee - 1 year ago 138

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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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)
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**