在Matlab中为每个局部函数导入函数 [英] Import functions in Matlab for every local function

查看:133
本文介绍了在Matlab中为每个局部函数导入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个m-file,其中有一些定义为局部函数的测试.它们是从主要功能调用的:

I have an m-file with a couple of tests defined as local functions. They are called from the main function:

function tests = main_function_test()
    tests = functiontests(localfunctions);
end

我在做具有一定容忍度的断言,所以我需要导入每个局部函数:

I am doing assertions with some tolerance, so I need to import in each local function:

import matlab.unittest.constraints.IsEqualTo;
import matlab.unittest.constraints.AbsoluteTolerance;

为了进行以下形式的断言:

in order to make assertions of the form:

verifyThat(testCase, actual, IsEqualTo(expected, ...
        'Within', AbsoluteTolerance(0.00001)));

是否可以只导入一次这些函数,以便可以在每个本地函数中重用它们?

Is it possible to import those functions just once so they can be reused in each local function?

推荐答案

每个

作用域是函数,该函数不共享父函数的导入列表.如果在MATLAB函数或脚本以及任何本地函数中需要导入列表,则必须为每个函数调用导入函数.

Scope is the function and the function does not share the import list of the parent function. If the import list is needed in a MATLAB function or script and in any local functions, you must call the import function for each function.

话虽这么说,您可以evalimport(字符串的单元格数组)的输出一起使用,但这是极差的编码实践,强烈建议您不要这样做.

That being said, you could use eval with the output from import (cell array of strings) but it's extremely poor coding practice and I highly recommend against doing it.

function trialcode
import matlab.unittest.constraints.IsEqualTo;
import matlab.unittest.constraints.AbsoluteTolerance;

importlist = import;
sub1(importlist)
end

function sub1(L)
for ii = 1:length(L)
    estr = sprintf('import %s', L{ii});
    eval(estr);
end
disp(import)
end

再次,从技术上讲这是可能的,但是请不要这样做.您几乎无法控制导入(并且控制逻辑可能比隐式导入首先要长),它很难调试,MATLAB的编译器无法优化,并且使代码非常不清楚.

Again, this is technically possible but please don't do it this way. You have little control over the imports (and controlling logic would likely be longer than implicitly importing them in the first place), it's difficult to debug, impossible for MATLAB's compiler to optimize, and makes the code tremendously unclear.

这篇关于在Matlab中为每个局部函数导入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆