我将如何做(例如)这样的事情:
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。但是,我似乎无法找到解释这类事情的任何有用的代码示例;因此这个问题。
答案 0 :(得分:0)
我不确定这是否完全符合您的所有要求,但您是否尝试过使用结构类?
答案 1 :(得分:0)
如果您的背景是C ++,那么您应该熟悉类和对象的概念。
以下是实施部分设计的快速示例:
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()