What is the meaning of Structure in Constructor function?

Started by 6 years ago2 replieslatest reply 6 years ago163 views

Hello,

In Object-Oriented Programming methodology, construction function is used to assign the data to the object variables. But in the following Matlab code, there is a structure in the constructure function and I am trying to understand this usage and how we can interpret the logical operators in the code below.

I am not sure if this is the right place asking this kind of question here but if you could explain I would be glad.

Here are my questions:

1-Could you please explain how it works and why a structure is used in the constructor function above?

2-In the constructor function there is a tilde (~) operator, how do we interpret the usage of this tilde operator here?

3-Is there any other way that can be used to express the same purpose here instead of using tilde?

5-What is the meaning of (~isfield(StructParameters)) logical function?

classdef myClass
properties
a;
d;
noInput;
end
methods
function obj=myClass(StructParameters)
if nargin==0
StructParameters.noInput=1;
else
StructParameters.noInput=0;
end

if ~isstruct(StructParameters)
error('Input argument has to be struct.')
else
F=fields(StructParameters);
for x=1:length(F)
obj.(F{x})=StructParameters.(F{x});
end
end

if ~isfield(StructParameters, 'a')
obj.a=[1 2; 4 5];
end

if ~isfield(StructParameters, 'd')
obj.d=[0 1; 4 5];
end
end

end

end
[ - ]

1: I'm not sure exactly what they're attempting, but it looks like they're constructing a structure F that matches the input structure.  The "why" is because sometimes you want to pass in structured data; more than that would have to come from the author.

2: The tilde in Matlab is a logical not: for a scalar, (a == 1) is the same as ~(a~=1) (this may or may not be the case if a is a vector -- trying to figure that out without doing a bunch of test cases would make my brain hurt).

3: Probably not, or at least it'd be dangerous.  If the "isfield" function is strict about returning a boolean, then you could say "isfield(whatever)==false", where 'false' in this context is whatever Matlab predefines as being a logical false (I'm not a Matlab guy: in Scilab it's '%F').

4: By context, it pretty much has to mean that it's telling you whether the argument is a structure or not.

5: isfield(StructParameters, 'a') will, I'm 99.44% certain, return true if the structure has a field named a.  ~isfield(StructParameters, 'a') should return false if the structure has a field named a, and true if it does not.  isfield(StructParameters) should probably generate an error message.

[ - ]