matlab - 在 Matlab 中的单个 .m 文件中导入多个类?

标签 matlab

我看过 MATLAB: alternative of Octave's function 'source' (import m-file) ,但我似乎无法弄清楚以下内容是如何工作的。这是用于 Matlab R2016b 的。

我正在查看 M_files_chap12.zip ,在那个 .zip 中,有两个文件:

  • WDFDiodeExample.m 可运行,并使用一些额外的类
  • WDFClasses.m 包含额外的类

这是 WDFClasses.m 的一个片段:

% WDFclasses.m
% ....

%----------------------WDF Class------------------------
classdef WDF < hgsetget % the WDF element superclass
    properties 
        PortRes % the WDF port resistance
    end
    methods
            function Volts = Voltage(obj)  % the voltage (V) over a WDF element
                Volts = (obj.WU+obj.WD)/2; % as defined in the WDF literature
            end
    end;
end
%----------------------Adaptor Class------------------------
classdef Adaptor < WDF % the superclass for ser. and par. (3-port) adaptors
    properties
        KidLeft % a handle to the WDF element connected at the left port
        KidRight % a handle to the WDF element connected at the right port
    end;
end
...

问题是,我似乎无法从该文件中导入这些类。我尝试在 WDFDiodeExample.m 的开头添加以下每个语句:

WDFClasses  %this will run WDFClasses.m; but % Class name and filename do not agree.
eval(fileread('WDFClasses.m')) % Error: Illegal use of reserved keyword "classdef".
run('WDFClasses.m') % Class name and filename do not agree.

...我得到了评论中写的错误。

似乎 MATLAB 希望每个文件一个类,而且它似乎无法识别打包在单个文件中的多个类——但是,为什么作者会选择像这样写WDFClasses.m,这样它就不能直接使用了?或者这在早期版本的 MATLAB 中是可能的,然后被禁用了吗?

最佳答案

原来,相关文献也提到了这一点:

It must be noted that all the presented classes are shown in a single M-file for compactness although in practice MATLAB requires each class to reside in an individual file. In other words, the classes ... should be split into seven different files in order for the model to run in MATLAB.

...所以我想,这就是它的工作方式...

关于matlab - 在 Matlab 中的单个 .m 文件中导入多个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44145284/

相关文章:

image - 我如何将 "plot"图像放在另一个具有不同颜色图的图像之上?

matlab - 如何在 Matlab 中使用谷歌翻译?

image - 在图片中创建一个钻石

matlab - 在对同一数据集进行训练后,您对两个完全相同的神经网络有何评价?

c++ - 变量改变应该不受影响(内存溢出?)

matlab - 为什么此表达式的计算结果为 0?

c - 从 VB.Net 读取 MatLab Simulink 值

matlab - 找到复杂函数具有实值的点

java - 在 MATLAB 中,我可以将 java boolean 值转换为 MATLAB 逻辑值吗?

matlab - 函数,在 MATLAB dna 复制中