Reputation: 2744
I've been trying to work with MATLAB classes & structs in order to develop a traffic simulation. I have not worked actively with MATLAB classes before, so it gets a bit tricky at times. This questions involves manipulating a struct, which is a property of a class.
Top-level access
vehicles_handle = VehiclesHandle;
vehicles_handle.CreateVehicles(InitialTrafficDensity);
vehicles_handle.vehicles(1)
Class definition
classdef VehiclesHandle
%VEHICLESHANDLE Summary of this class goes here
% Detailed explanation goes here
properties
active_vehicles_count
vehicles
end
methods (Access = public)
function obj = VehiclesHandle
obj.active_vehicles_count = 0;
obj.vehicles = struct('lane',0,'position',0,'velocity',0);
end
function obj = CreateVehicles(obj,InitialTrafficDensity)
obj.active_vehicles_count = obj.active_vehicles_count + 1;
obj.vehicles(1).lane = 1;
obj.vehicles(1).position = 3;
obj.vehicles(1).velocity = 3;
obj.vehicles(2).lane = 2;
obj.vehicles(2).position = 3;
obj.vehicles(2).velocity = 3;
end
Now, I can't see the output as expected (which is vehicles_handle.vehicles(1)), I see them the properties of the vehicle 1 as 0's. The situation changes, of course, when I put then in the function VehiclesHandle, but I want to handle creation of vehicles this way.
I know that the code might not be the most efficient way to handle this, but I really do want to learn about handling a struct in this class without pain. Thanks for all the constructive comments and help in advance.
Upvotes: 0
Views: 106
Reputation: 2343
Getting rid of the problem is quite easy:
classdef VehiclesHandle
has to be
classdef VehiclesHandle < handle
And to understand why, please read Comparison of Handle and Value Classes.
Upvotes: 1