Structures in MATLAB

MATLAB Tutorial

🧱 Structures in MATLAB

Structures (structs) in MATLAB let you group related data under named fields—perfect for organizing complex information like records, configurations, and results.

MATLAB is developed by MathWorks.


🔹 What Is a Structure?

A structure is a data type that stores fields (named attributes), each of which can hold any data type (numbers, strings, arrays, cells, even other structs).

Think of it like a record:


 


1️⃣ Creating a Structure

🔸 Using Dot Notation


 

Output

Name: 'Amit'
Age: 20
Marks: 85

🔸 Using struct() Function


 


2️⃣ Accessing Structure Fields


 

Output

Sara
90

3️⃣ Modifying Structure Fields


 

Output

95

4️⃣ Structure Array (Multiple Records)


 

🔸 Access a Specific Record


Output

Sara

📌 Very common in real-world datasets.


5️⃣ Looping Through a Structure Array


 


6️⃣ Nested Structures

Structures can contain other structures.


 

Output

Delhi

7️⃣ Adding & Removing Fields

🔸 Add a New Field


🔸 Remove a Field


 


8️⃣ Checking Fields


 


9️⃣ Converting Between Structures & Tables


 

📌 Useful for data analysis and exporting.


⚠️ Important Notes

  • Fields are accessed using dot (.) notation

  • Structures can grow dynamically

  • Structure arrays are slower than numeric arrays but very flexible

  • Ideal for heterogeneous, labeled data


🎯 Interview Questions: Structures in MATLAB

🔹 Q1. What is a structure in MATLAB?

Answer:
A data type that stores related data in named fields.


🔹 Q2. How do you access a field in a structure?

Answer:
Using dot notation (S.fieldName).


🔹 Q3. Can a structure store different data types?

Answer:
Yes.


🔹 Q4. What is a structure array?

Answer:
An array where each element is a structure with the same fields.


🔹 Q5. How do you remove a field from a structure?

Answer:
Using rmfield().


🔹 Q6. Can structures be nested?

Answer:
Yes, structures can contain other structures.


🔹 Q7. Difference between cell array and structure?

Answer:
Cell arrays use indices; structures use named fields.


Summary

  • Structures organize related data using fields

  • Support mixed data types

  • Can be arrays and nested

  • Essential for clean, real-world MATLAB programs

You may also like...