How to Put These Vectors in a Matrix?
1 次查看(过去 30 天)
显示 更早的评论
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]
0 个评论
采纳的回答
Stephen23
2017-3-5
编辑:Stephen23
2017-3-5
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 个评论
Stephen23
2017-3-5
编辑:Stephen23
2017-3-5
@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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!