0

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.