Bird
0
0

How do you correctly initialize a structure array employee with fields FirstName and Years for two employees in MATLAB?

easy📝 Syntax Q3 of 15
MATLAB - Cell Arrays and Structures
How do you correctly initialize a structure array employee with fields FirstName and Years for two employees in MATLAB?
Aemployee(1).FirstName = 'Alice'; employee(1).Years = 5; employee(2).FirstName = 'Bob'; employee(2).Years = 3;
Bemployee = struct('FirstName', {'Alice', 'Bob'}, 'Years', {5, 3});
Cemployee = struct('FirstName', ['Alice', 'Bob'], 'Years', [5, 3]);
Demployee.FirstName = ['Alice', 'Bob']; employee.Years = [5, 3];
Step-by-Step Solution
Solution:
  1. Step 1: Use indexed assignment

    Assign fields for each element separately using indices.
  2. Step 2: Assign field values

    Set FirstName and Years for each employee individually.
  3. Final Answer:

    employee(1).FirstName = 'Alice'; employee(1).Years = 5; employee(2).FirstName = 'Bob'; employee(2).Years = 3; correctly initializes the structure array.
  4. Quick Check:

    Check if each element has both fields assigned properly. [OK]
Quick Trick: Assign fields element-wise using indices [OK]
Common Mistakes:
  • Using cell arrays incorrectly in struct
  • Assigning arrays directly to fields expecting scalars
  • Confusing struct array with struct of arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More MATLAB Quizzes