Matlab-可以添加不同“的”的类;项目“;
我将如何着手做(例如)这样的事情:Matlab-可以添加不同“的”的类;项目“;,matlab,function,class,Matlab,Function,Class,我将如何着手做(例如)这样的事情: house = Building('blue'); % creates an object representing a 'blue' house % based on a class called building room1 = Room('kitchen', 9); % creates a room object representing a kitchen
house = Building('blue'); % creates an object representing a 'blue' house
% based on a class called building
room1 = Room('kitchen', 9); % creates a room object representing a kitchen
% with a size of 9 m^2
room2 = Room('lobby', 5); % creates a room object representing the lobby
% with a size of 5 m^2
house.add_room(room1); % assigns the two rooms to the house object
house.add_room(room2); %
house.room_count(); % should return the number 2
house.size('kitchen'); % should return the size of the kitchen, i.e. 9
house.size(); % should return the size of the entire house, i.e. 14
house.room_list(); % should return a list of the rooms in the house
% which could e.g. be the string 'kitchen lobby'
这个例子完全是理论性的,我只是想知道如何在Matlab中实现类似的东西,以了解该语言是如何工作的。我将非常感谢您的任何帮助。我的背景是C++中的“基本”语言,但我想学习MATLAB。然而,我似乎找不到任何有用的代码示例来解释这类事情;因此产生了这个问题。我不确定这是否完全符合您的所有要求,但是您是否尝试过使用structure类
< P>如果你的背景是C++,那么你应该熟悉类和对象的概念。 下面是实现部分设计的快速示例: m房间
MATLAB有大量关于面向对象编程的文档,因此我将向您介绍这些文档以获取更多信息:,这正是我想要的,谢谢!是的,我看过你的推荐信,但他们没有真正深入地解释事情。也许还有一个后续问题。如果我有一个名为house_part的超级类和派生类,比如room(即classdef room
classdef Room < handle
properties
name
area
end
methods
function obj = Room(name, a)
if nargin < 2, a = 1; end
obj.name = name;
obj.area = a;
end
end
end
classdef Building < handle
properties
color
rooms
end
methods
function obj = Building(clr)
obj.color = clr;
obj.rooms = Room.empty(1,0);
end
function add_room(obj, r)
if ~isa(r, 'Room'), return, end
obj.rooms(end+1) = r;
end
function num = room_count(obj)
num = numel(obj.rooms);
end
function list = room_list(obj)
list = {obj.rooms.name};
end
function sz = area(obj)
sz = 0;
for i=1:numel(obj.rooms)
sz = sz + obj.rooms(i).area;
end
end
end
end
house = Building('blue');
house.add_room(Room('kitchen',9));
house.add_room(Room('lobby',5));
house.room_count()
house.room_list()
house.area()