Why do I get the error "Subscripted assignment dimension mismatch" when using a cell array in a structure field?

I have the following lines of code which work: 
layers(1)=struct('test', 'ABC', 'value', 0.50);
layers(2)=struct('test', 'DEF', 'value', []);
I would like to combine the "test" and "value" fields into a single field like this: 
layers(1)=struct('test', {'ABC', 0.50});
layers(2)=struct('test', {'DEF'});
This gives the error message "Subscripted assignment dimension mismatch." 
Is there a way to put a 1x2 cell into a single field in the structure? 

 採用された回答

You are getting a "Subscripted assignment dimension mismatch" error because MATLAB is using a syntax where you use a cell array to specify each of the fields in a structure array. For example, the following code creates a 1x2 struct array:
a = struct('test', {1, 2};)
You receive an error in your code occurs because you are specifying a scalar structure with the left hand syntax "layers(1)". 
The workaround is to add the cell array to the structure using the dot-notation for any entries that you would like to have variable-length cell arrays.Here is an example:
a = struct('singlevalue', 3);
a.multivalue = {1, 2};
Another workaround is to use a nested cell array. Please see the following:
a (1) = struct('singlevalue', 3, 'multivalue', {{1,2}});
In the documentation page for "struct", you can see a description of how MATLAB structs interpret a cell array parameter. Please refer to the second syntax description (s = struct(<https://www.mathworks.com/help/matlab/ref/struct.html#inputarg_field field>,<https://www.mathworks.com/help/matlab/ref/struct.html#inputarg_value value>)) at the following link:
 

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by