Is it possible somehow make vector of structure?
Ältere Kommentare anzeigen
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.
Antworten (3)
Azzi Abdelmalek
am 26 Jun. 2015
Bearbeitet: Azzi Abdelmalek
am 26 Jun. 2015
a=rand(1,10);
b=rand(1,10);
s=struct('field1',num2cell(a),'field2',num2cell(b))
John D'Errico
am 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 Kommentare
Mr M.
am 28 Jun. 2015
John D'Errico
am 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.
Guillaume
am 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.
Kategorien
Mehr zu Structures finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!