A structure array in MATLAB can only contain structures with identical fields. By first creating an array of empty structures1 and then trying to fill it with SVMStruct
structures, you try to create a mixed array with some empty structures, and some SVMStruct
structures. This is not possible, thus MATLAB complains about "dissimilar structures" (not-equal structures: empty vs. SVMStruct
).
To allocate an array of structs, you will have to specify all fields during initialization and fill them all with initial values - which is rather inconvenient in this case. A very simple alternative is to drop this initialization, and run your loop the other way around2,3:
for ii=sizeOfLabels:-1:1
model(ii) = svmtrain(train_data,labels(:,ii),'Options', options);
end
That way, for ii=sizeOfLabels
, e.g. ii=100
, MATLAB will call model(100)=...
, while model
doesn't exist yet. It will then allocate all space needed for 100 SVMStruct
s and fill the first 99 instances with empty values. That way you pre-allocate the memory, without having to worry about initializing the values.
1Note: if e.g.
size=5
, calling
repmat(struct(),size)
will create a
5-by-5 matrix of empty structs. To create a
1-by-5 array of structs, call
repmat(struct(),1,size)
.
2Don't use size
as a variable name, as this is a function. If you do that, you can't use the size
function anymore.
3i
and j
denote the imaginary unit in MATLAB. Using them as a variable slows the code down and is error-prone. Use e.g. k
or ii
for loops instead.