Is it possible somehow make vector of structure?

79 views (last 30 days)
Mr M.
Mr M. on 26 Jun 2015
Answered: Guillaume on 28 Jun 2015
So instead of struct1, struct2, struct3, I would like to index them somehow: struct(i) or struct{i} or something like this, where the index can be a variable.

Answers (3)

Azzi Abdelmalek
Azzi Abdelmalek on 26 Jun 2015
Edited: Azzi Abdelmalek on 26 Jun 2015
a=rand(1,10);
b=rand(1,10);
s=struct('field1',num2cell(a),'field2',num2cell(b))

John D'Errico
John D'Errico on 26 Jun 2015
Did you try it?
struct(1).a = 3;
struct(2).a = 5;
struct
struct =
1x2 struct array with fields:
a
[struct.a]
ans =
3 5
  2 Comments
Mr M.
Mr M. on 28 Jun 2015
Sorry not to be precise, but I need different kind of structure in a data structure. So struct(1) and struct(2) has to be different. For example struct(1) has .a but struct(2) has not, instead struct(2).c for example.
John D'Errico
John D'Errico on 28 Jun 2015
@MR M:
If you wish to have a struct where the different elements of an array of structs have different fields, this is not possible. For example:
struct(1).a = 1
struct =
a: 1
struct(2).b= pi
struct =
1x2 struct array with fields:
a
b
struct(1)
ans =
a: 1
b: []
struct(2)
ans =
a: []
b: 3.1416
As you can see, both elements of the vector of structs ended up with both a and b as fields. The undefined fields were left empty.
This is as much as you can do with pure structs. Sorry. Not everything is possible.
Of course, if you are willing to have a cell array of structs, then you could do this. Perhaps this would be acceptable to you.
C{1}.a = 1;
C{2}.b = pi;
C
C =
[1x1 struct] [1x1 struct]
C{1}
ans =
a: 1
C{2}
ans =
b: 3.1416
Working with that array of structs will be slightly less clean of course. You would probably need to use cellfun in some cases, depending on what you were doing.

Sign in to comment.


Guillaume
Guillaume on 28 Jun 2015
structure arrays are homogeneous, all the structures have to be identical. If you want an heterogeneous container, use cell arrays.
c = {struct('a', 5), struct('c', 10)};
Accessing the fields of each structure is straightforward:
c{1}.a
c{2}.c
but because the container itself is not a structure (unlike structure arrays), you can't pass it to functions that expect structures. You can always use cellfun to iterate over the elements.
There's also no way to ensure that the cell array only contain structures.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!