0

I want to train data on various labels using svm and want svm model as array of struct. I am doing like this but getting the error:

Subscripted assignment between dissimilar structures.

Please help me out

model = repmat(struct(),size);
for i=1:size
     model(i) = svmtrain(train_data,labels(:,i),'Options', options);    
end
Smittey
  • 2,475
  • 10
  • 28
  • 35
garg
  • 3
  • 2
  • What is `size`? Further, `size()` is a function. If you name a variable `size`, then you won't be able to call the `size()` function anymore. Usually, this is a bad idea - I'd consider changing this variable name to something like `sizeOfWhatever`, `whateverSize`, .... – hbaderts Apr 06 '16 at 10:19
  • size is actually a variable which decides the length of array. I renamed this with some other variable but still I am getting same error. – garg Apr 06 '16 at 11:26

1 Answers1

0

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 SVMStructs 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.

Community
  • 1
  • 1
hbaderts
  • 14,136
  • 4
  • 41
  • 48