How can I fill a structure array with a scalar array?
23 views (last 30 days)
Show older comments
I have a structure array like this:
myStruct=repmat(struct('field1',0),10,1);
and I have a double array:
myarray = [1 2 3 4 5 6 7 8 9 10];
If I wanto to initialize mystruct with my array I have to do this>
for i = 1:10 mystruct(ii).field1 = myarray(ii); end
There is a way to do this with one row of statement?
If I do
mystruct.field1 = myarray
I get the error:
"Scalar structure required for this assignment"
I've also tried:
mystruct(:).field1 = myarray(:)
but the error was: "Expected one output from a curly brace or dot indexing expression, but there were 10 results."
what can I do?
0 Comments
Accepted Answer
Stephen23
on 26 May 2017
Edited: Stephen23
on 26 May 2017
If you have a non-scalar structure and that you want to allocate new data to the same field of each element of that structure, then this is easiest using a comma-separated list:
>> myStruct=repmat(struct('oldfield',0),10,1);
>> myarray = [1,2,3,4,5,6,7,8,9,10];
>> C = num2cell(myarray);
>> [myStruct.newfield] = C{:};
3 Comments
More Answers (2)
utsav kakkad
on 22 Oct 2018
this can work out if you can assign values to it manually by typing it out from the key board but when you have to make an assignment programmatically what shall you do? I am working on one such problem right now: I have a structure and I need to assign a value to it , I cannot make a comma separated list here. Any suggestions? Matlab documentation on structures doesn't help me out
1 Comment
Stephen23
on 24 Oct 2018
Edited: Stephen23
on 24 Oct 2018
"I cannot make a comma separated list here."
There are many possible combinations of structure and array:
- assign one scalar array to one field of a scalar structure.
- assign one non-scalar array to one field of a scalar structure.
- assign one non-scalar array to separate fields of a scalar structure.
- assign elements of one array to separate fields of a scalar structure.
- assign one scalar array to one field of a non-scalar structure.
- assign elements of one non-scalar array to one field of a non-scalar structure.
- ... etc.
Some of these can be solved using a comma-separated list, whereas some of them require other syntaxes. However you did not give us any actual information on your structure, on your array, and on exactly which elements you want to assign and in what way. This makes it very hard for us to help you.
"Any suggestions?"
Give us example data, and/or an actual description of your data, and also explain exactly how you want the data to be assigned to the structure.
See Also
Categories
Find more on Structures in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!