简体   繁体   中英

Use workspace variables in a Matlab function

I'd like to use the data that are loaded to my workspace in a Matlab function. This is the beginning of my function.

function [totalProfit] = compute(p,exit)

%% Declaration of variables

entry=0;
T = length(data);
.
.
.
end

I'm getting an error:

Undefined function or variable 'data'.

Where is the error?

The variable data was probably defined outside of the function, so it is out of scope.

Pass data as a parameter to compute and then it will be available inside the function.

You can use evalin to work with variables from another workspace. In your example this could be

T = evalin('caller','length(data)')

But please note that in most cases you get cleaner code if you define the variable as input argument for the function . So for your case this would be

function [totalProfit] = compute(p,exit,data)    
   T = length(data) ;
end

Ran is correct, but I wanted to mention something else. In general, only variables that are passed as arguments to a function are able to be used inside that function, so if you want to use your existing variables inside the function, pass them as input arguments.

It is possible to create global variables which allow you to use them inside functions without passing them as arguments, but it's usually not the best way of writing code. The times where I have used global variables are where I am calling multiple functions from a single script, and I have some constants that will be used by all the functions (for example gravity is a common one). An alternative to global variables is to use a struct, with the variables you want to pass to the function in it, so you only need one extra input argument, but you still have to be a bit careful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM