create an array of single struct

조회 수: 16 (최근 30일)
Aditya Jain
Aditya Jain 2015년 11월 9일
댓글: Guillaume 2015년 11월 9일
structElement = struct('a1','', 'a2', '', 'a3', '', 'a4', '');
s1 = repmat(structElement, [1,1]);
The above code gives a 1x1 struct
s2 = repmat(structElement, [2,1]);
The above code results in a 2x1 struct
If I do s2(1) it returns a struct
If I do s1(1) it returns a1.
How can I create s1, such that s1(1) will give me back a struct. Basically I want to create an array of single struct.
  댓글 수: 2
Adam
Adam 2015년 11월 9일
편집: Adam 2015년 11월 9일
Both those syntaxes return the full struct. They do in Matlab R2015b that I am using.
s1 = structElement;
would do though. The repmat instruction is redundant.
Guillaume
Guillaume 2015년 11월 9일
I'm fairly certain they've done so in every version of matlab (barring any bug).
It would never make any sense for an index to return a field of a structure. Particularly since everything in matlab, including scalar structures, is always an array.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2015년 11월 9일
"If I do s1(1) it returns a1." No, it also returns a structure.
Both s1 and structElement are arrays of a single struct:
>>s1(1)
ans =
a1: ''
a2: ''
a3: ''
a4: ''
>>size(s1)
ans =
1 1
>>size(structElement)
ans =
1 1
Everything in matlab is an array. Scalars (numbers, structs, objects, etc.) are stored as array of size 1x1
  댓글 수: 3
Walter Roberson
Walter Roberson 2015년 11월 9일
s2 = repmat({structElement}, [2,1]);
Guillaume
Guillaume 2015년 11월 9일
You can create cell arrays of structures the same way you create cell arrays of numbers, by plain assignment, using arrayfun / cellfun, using num2cell, etc.
s = struct('a', {1 2 3 4 5}, 'b', ''); %creates a 1x5 array of struct
c = num2cell(s); %convert matrix to cell array
Another way:
s = struct('a', '', 'b', '');
c = cell(2, 5);
c(:) = {s};
However, if all the structures have the same fields, I don't see the point of storing them in a cell array.

댓글을 달려면 로그인하십시오.

추가 답변 (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