Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Difference between the given syntax

조회 수: 1 (최근 30일)
Swati Sarangi
Swati Sarangi 2020년 11월 3일
마감: MATLAB Answer Bot 2021년 8월 20일
Hi All,
I've doubt in interpreting following lines . Can somebody clarify that ?
cube.id(i)=lcount
cube(1).id=lcount1
Any help will be appreciated.
Thanks in advance!

답변 (2개)

Ameer Hamza
Ameer Hamza 2020년 11월 3일
In case of
cube.id(i)=lcount
'cube' is a scalar struct and id is an array. And In case of
cube(1).id=lcount1
'cube' is a struct array, while 'id' is a scalar.

Steven Lord
Steven Lord 2020년 11월 3일
편집: Steven Lord 2020년 11월 3일
As Ameer Hamza said, the difference is whether you want your struct array to be a scalar struct array with a field that is not scalar or whether you want a nonscalar struct array with fields that are scalar. Let's look at a slightly different example.
>> C1.id(2) = 42;
>> C2(2).id = 99;
>> whos C1 C2
Name Size Bytes Class Attributes
C1 1x1 184 struct
C2 1x2 184 struct
C1 and C2 have different sizes.
>> disp(C1)
id: [0 42]
C1 only has one element, that element has one field, and that field has two elements.
>> disp(C2)
1×2 struct array with fields:
id
>> disp(C2(1))
id: []
>> disp(C2(2))
id: 99
C2 has two elements, each of those elements have one field, and the second of those elements has a field with one element.
One key question you should ask when deciding between a struct containing an array or an array of structs is how are you likely to want to "slice" your data. In C1, I can easily operate on each element of id with a loop, but if it had another field say name I would have to operate on each field separately. In C2 operating on all the id fields will be a bit more challenging, but I can easily extract both the id and the name for an individual element.
>> C1.name = ["Cleve", "Jack"];
>> C2(1).name = "Cleve";
>> C2(2).name = "Jack";
>> C2(1).id = 0;
% Display both ID and name from one of the people stored in C1
>> disp(C1.id(1))
0
>> disp(C1.name(1))
Cleve
% Display both ID and name from one of the people stored in C2
>> disp(C2(1))
id: []
name: "Cleve"
% Display both ID values for people in C1
>> disp(C1.id)
0 42
% Display both ID values for people in C2 -- note the square brackets
>> disp([C2.id])
0 99

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by