How to Put These Vectors in a Matrix?

조회 수: 3 (최근 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
Rightia Rollmann
Rightia Rollmann 2017년 3월 5일
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 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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by