How to Put These Vectors in a Matrix?

1 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2017 年 3 月 5 日
編集済み: Stephen23 2017 年 3 月 5 日
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]

採用された回答

Stephen23
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
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 件)

カテゴリ

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!

Translated by