Azzera filtri
Azzera filtri

How to Put These Vectors in a Matrix?

1 visualizzazione (ultimi 30 giorni)
A.B.G = [1 2 3];
A.C.G = [4 5 6];
A.D.G = [7 8 9];
A.E.G = [10 11 12];
A.F.G = [13 14 15];
so it will look like:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
It's just an example and A has more than 5 fields, so please do not suggest something like this:
[A.B.G; A.C.G; A.D.G; A.E.G; A.F.G]

Risposta accettata

Stephen23
Stephen23 il 5 Mar 2017
Modificato: Stephen23 il 5 Mar 2017
Here is one way:
>> A.B.G = [1 2 3];
>> A.C.G = [4 5 6];
>> A.D.G = [7 8 9];
>> A.E.G = [10 11 12];
>> A.F.G = [13 14 15];
>> cell2mat(structfun(@(s){s.G},A))
ans =
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
Although to be honest your code would be much faster and simpler if you used a non-scalar structure, because then you can simply do this:
>> S(1).G = [1 2 3];
>> S(2).G = [4 5 6];
>> S(3).G = [7 8 9];
>> S(4).G = [10 11 12];
>> S(5).G = [13 14 15];
>> vertcat(S.G)
ans =
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
Using indices will be much simpler than trying to access fieldnames, and woudl allow you to very simply solve your other question by using indices to select the parts of the structur that you want:
>> vertcat(S([1,3,4]).G)
ans =
1 2 3
7 8 9
10 11 12
Do not make your code more complicated than it needs to be. Good data storage makes your code simpler and neater too.
  4 Commenti
Rightia Rollmann
Rightia Rollmann il 5 Mar 2017
Thank you so much for your patience and brilliance!
Your suggestion of using non-scalar structure is generally great! Specifically speaking for this data set, I thought if I name each field separately, it would be easier to recognize them later by their field names
Stephen23
Stephen23 il 5 Mar 2017
Modificato: Stephen23 il 5 Mar 2017
@Rightia Rollmann: it is better to store meta-data as data in its own right, e.g.:
S(1).data = [1,2,3]; % measurements
S(1).name = 'anna';
S(2).data = [4,5,6];
S(2).name = 'bob';
rather than trying to make the fieldnames equal to the subjects names. This is simpler and easier to write code for, which means your code will be faster and less buggy.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by