Challenge - 5 Problems
Dynamic Field Names Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this code using dynamic field names?
Consider the following MATLAB code that uses dynamic field names in a struct. What will be the output displayed?
MATLAB
fieldName = 'score'; student.(fieldName) = 95; disp(student.score);
Attempts:
2 left
💡 Hint
Dynamic field names allow you to use a variable as the field name in a struct.
✗ Incorrect
The variable 'fieldName' holds the string 'score'. Using student.(fieldName) = 95; sets the field 'score' of struct 'student' to 95. Displaying student.score prints 95.
❓ Predict Output
intermediate2:00remaining
What does this code print when using dynamic field names with a loop?
Look at this MATLAB code snippet. What will be the output after running it?
MATLAB
fields = {'a', 'b', 'c'};
for i = 1:length(fields)
data.(fields{i}) = i*10;
end
disp(data.b);Attempts:
2 left
💡 Hint
Each field in 'data' is set to i*10 where i is the loop index.
✗ Incorrect
The loop assigns data.a = 10, data.b = 20, data.c = 30. Displaying data.b prints 20.
🔧 Debug
advanced2:00remaining
Identify the error in this dynamic field name usage
This MATLAB code tries to assign a value using a dynamic field name but causes an error. What is the cause?
MATLAB
field = 123; record.(field) = 'value';
Attempts:
2 left
💡 Hint
Field names in structs must be text, not numbers.
✗ Incorrect
In MATLAB, struct field names must be strings or character vectors. Using a numeric value as a field name causes an error.
📝 Syntax
advanced2:00remaining
Which option correctly creates a struct with dynamic field names?
Select the MATLAB code snippet that correctly creates a struct with dynamic field names from variables 'f1' and 'f2'.
Attempts:
2 left
💡 Hint
Use parentheses and dot notation with a string variable for dynamic field names.
✗ Incorrect
Option B uses the correct syntax: person.(f1) assigns to the field named by the string in f1. Option B assigns to fields literally named 'f1' and 'f2'. Option B uses curly braces which is invalid for struct fields. Option B tries to assign multiple fields at once which is invalid syntax.
🚀 Application
expert2:00remaining
How many fields does the struct have after this code runs?
Given the following MATLAB code, how many fields does the struct 'info' contain at the end?
MATLAB
fields = {'x', 'y', 'x', 'z'};
info = struct();
for k = 1:length(fields)
info.(fields{k}) = k;
endAttempts:
2 left
💡 Hint
Struct fields must be unique; repeated field names overwrite previous values.
✗ Incorrect
The field 'x' appears twice. The second assignment overwrites the first. The final fields are 'x', 'y', and 'z', so total 3 fields.