我見過MATLAB: alternative of Octave's function 'source' (import m-file),但我似乎無法弄清楚以下是如何工作的。這是用於Matlab R2016b。在Matlab中的單個.m文件中導入多個類?
我看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中可能會出現這種情況,然後被禁用?
是,MATLAB需要每個文件只有一個類。 –