简体   繁体   English

在Matlab函数中使用工作区变量

[英]Use workspace variables in a Matlab function

I'd like to use the data that are loaded to my workspace in a Matlab function. 我想使用Matlab函数中加载到我的工作区中的数据。 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. data作为参数传递进行compute ,然后在函数内部可用。

You can use evalin to work with variables from another workspace. 您可以使用evalin处理来自另一个工作空间的变量。 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. 全局变量的另一种选择是使用结构,将要传递给函数的变量包含在其中,因此您只需要一个额外的输入参数,但是仍然要小心一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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