Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

Difference between the given syntax

2 visualizzazioni (ultimi 30 giorni)
Swati Sarangi
Swati Sarangi il 3 Nov 2020
Chiuso: MATLAB Answer Bot il 20 Ago 2021
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!

Risposte (2)

Ameer Hamza
Ameer Hamza il 3 Nov 2020
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 il 3 Nov 2020
Modificato: Steven Lord il 3 Nov 2020
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

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by