也是想用个单独建的函数调用已经建好的函数文件中子函数,搜到这个贴子。
matlab的确不允许从外部调用函数文件中的子函数。
lz想用类来实现这个功能是对的,看了一下matlab中的类定义,的确这样就可以实现了。
matlab帮助里搜“Develop Classes — Typical Workflow”,有类声明和调用例子,有过C++ OOP开发经验的做这个应该很简单。
顺手贴一下示例代码:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Class Definition
classdef BankAccount < handle
properties (Hidden)
AccountStatus = 'open';
end
% The following properties can be set only by class methods
properties (SetAccess = private)
AccountNumber
AccountBalance = 0;
end
% Define an event called InsufficientFunds
events
InsufficientFunds
end
methods
function BA = BankAccount(AccountNumber,InitialBalance)
BA.AccountNumber = AccountNumber;
BA.AccountBalance = InitialBalance;
% Calling a static method requires the class name
% addAccount registers the InsufficientFunds listener on this instance
AccountManager.addAccount(BA);
end
function deposit(BA,amt)
BA.AccountBalance = BA.AccountBalance + amt;
if BA.AccountBalance > 0
BA.AccountStatus = 'open';
end
end
function withdraw(BA,amt)
if (strcmp(BA.AccountStatus,'closed')&& BA.AccountBalance < 0)
disp(['Account ',num2str(BA.AccountNumber),' has been closed.'])
return
end
newbal = BA.AccountBalance - amt;
BA.AccountBalance = newbal;
% If a withdrawal results in a negative balance,
% trigger the InsufficientFunds event using notify
if newbal < 0
notify(BA,'InsufficientFunds')
end
end % withdraw
end % methods
end % classdef
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
classdef AccountManager
methods (Static)
function assignStatus(BA)
if BA.AccountBalance < 0
if BA.AccountBalance < -200
BA.AccountStatus = 'closed';
else
BA.AccountStatus = 'overdrawn';
end
end
end
function addAccount(BA)
% Call the handle addlistener method
% Object BA is a handle class
addlistener(BA, 'InsufficientFunds', ...
@(src, evnt)AccountManager.assignStatus(src));
end
end
end
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Using the BankAccount Class
The BankAccount class, while overly simple, demonstrates how MATLAB classes behave. For example, create a BankAccount object with a serial number and an initial deposit of $500:
BA = BankAccount(1234567,500);
BA.AccountNumber
ans =
1234567
BA.AccountBalance
ans =
500
BA.AccountStatus
ans =
open
Now suppose you make a withdrawal of $600, which results in a negative account balance:
BA.withdraw(600)
BA.AccountBalance
ans =
-100
BA.AccountStatus
ans =
overdrawn
When the $600 withdrawal occurred, the InsufficientsFunds event was triggered. Because the AccountBalance is not less than –$200, the AccountStatus was set to overdrawn:
BA.withdraw(200)
BA.AccountBalance
ans =
-300
BA.AccountStatus
ans =
closed
Now the AccountStatus has been set to closed by the listener and further attempts to make withdrawals are blocked:
BA.wit