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