How to create multiple objects and add values in a for loop?
7 views (last 30 days)
Show older comments
I have the following function which take as inputs the name of the feature I want to examine on my data and its corresponding class I have created.
classdef FeatureManager < handle
properties
features;
dimensions;
isRun;
end
methods
function obj = FeatureManager()
obj.isRun = false;
end
function addFeature(obj,featureName,featureClass)
if isfield(obj.features,featureName)
warning(['feature name ' featureName ' was already registered, overwriting']);
end
obj.features.(featureName) = featureClass;
obj.isRun = false;
end
end
end
In another script I have created a cell array with the names of the features I want to examine. In a for loop I try to automatically assign each name and the name of its class to the object.
mgr = FeatureManager();
for i = numel(DwtNames)
for lvl = 3:5
mgr.addFeature([DwtNames{i},'_',num2str(lvl)], DwtFeature(lvl,DwtNames{i}));
end
end
The DwtFeature Class:
classdef DwtFeature < Feature
properties
type;
lvl;
end
methods
function obj = DwtFeature(lvl,type)
if ~any(strcmp(type,{'haar','db8','sym4','sym8','bior1.3',...
'bior2.2','coif3','coif4'}))
error(['unsupported DWT type ' type ]);
end
obj.type = type;
obj.lvl = lvl;
end
function featureSize = init(obj,dataSize)
data = rand(dataSize,1);
res = wavedec(data,obj.lvl,obj.type);
featureSize = length(res(:));
end
function features = run(obj,data)
features = wavedec(data,obj.lvl,obj.type);
end
end
end
But the problem is that only the last features are written as these overwrite the previous feature names. How can I overcome this problem ?
Thank you in advance!
1 Comment
Adam
on 21 Jul 2017
This seems like one of those many problems that would be trivial to spot the problem using the debugger far more so than just staring at code trying to work out what is wrong.
Just put breakpoints in on key lines, check what featureName is being passed to your function each time and follow it through to see when/why the same feature name is being overwritten or others are not being written at all.
Answers (1)
Guillaume
on 21 Jul 2017
I can't reproduce the problem with the code you've posted:
>> DwtNames = {'a', 'b', 'c'}; %dummy names
>> DwtFeature = @(l, n) sprintf('%s_%d', n, l); %dummy function that doesn't do much
>> mgr = FeatureManager();
for i = numel(DwtNames)
for lvl = 3:5
mgr.addFeature([DwtNames{i},'_',num2str(lvl)], DwtFeature(lvl,DwtNames{i}));
end
end
>> mgr
mgr =
FeatureManager with properties:
features: [1×1 struct]
dimensions: []
isRun: 0
>> mgr.features
ans =
struct with fields:
c_3: 'c_3'
c_4: 'c_4'
c_5: 'c_5'
All three fields were created.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!