myDynamicClass

by

 

Create a set of objects from a text file.

myDynamicClass
classdef myDynamicClass < dynamicprops
    properties (Hidden, SetAccess = immutable)
        DataFile = 'none';
        Format = 'not-given'
        Class = 'member'
        Fields = 'none'
        Members = 'self'
    end
    methods
        function mDC = myDynamicClass(datafile,format)
            if nargin==0,return,end % no-arg constructor
            if nargin>0,mDC.DataFile = datafile;end
            if nargin>1,mDC.Format = ['%s',format];end
            fid = fopen(mDC.DataFile,'r');
            try
                header = textscan(fid,'%s',1,'Delimiter','\n');
                header = textscan(header{1}{1},'%s');
                mDC.Class = header{1}{1};
                mDC.Fields = header{1}(2:end);
                if strcmp(mDC.Format,'not-given')
                    dataLines = textscan(fid,'%s','Delimiter','\n');
                    for n = 1:length(dataLines{1})
                        data = textscan(dataLines{1}{n},'%s');
                        mDC.Members{n} = data{1}{1};
                        data = data{1}(2:end);
                        testType = cellfun(@(x)str2num(x),data,'UniformOutput',false); %#ok<ST2NM>
                        iNumericType = ~cellfun(@(x)isempty(x),testType);
                        if any(iNumericType)
                            [data{iNumericType}] = testType{iNumericType};
                        end
                        mDC.addprop(mDC.Members{n});
                        mDC.(mDC.Members{n}) = myDynamicClass;
                        for m = 1:length(mDC.Fields)
                            mDC.(mDC.Members{n}).addprop(mDC.Fields{m});
                            mDC.(mDC.Members{n}).(mDC.Fields{m}) = data{m};
                        end
                    end
                else
                    % mDC.NumMembers = length(strfind(mDC.Format,'%'))-1;
                    data = textscan(fid,mDC.Format);
                    mDC.Members = data{1};
                    for n = 1:length(mDC.Members)
                        mDC.addprop(mDC.Members{n});
                        mDC.(mDC.Members{n}) = myDynamicClass;
                        for m = 1:length(mDC.Fields)
                            mDC.(mDC.Members{n}).addprop(mDC.Fields{m});
                            if iscell(data{m+1})
                                mDC.(mDC.Members{n}).(mDC.Fields{m}) = data{m+1}{n};
                            elseif isnumeric(data{m+1})
                                mDC.(mDC.Members{n}).(mDC.Fields{m}) = data{m+1}(n);
                            else
                                error('huh:huh','huh?')
                            end
                        end
                    end
                end
            catch me
                fclose(fid);
                rethrow(me)
            end
            fclose(fid);
        end
    end
end

Contact us