0
0
MATLABdata~20 mins

Dynamic field names in MATLAB - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Dynamic Field Names Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
A95
BError: Undefined function or variable 'score'.
Cstudent.score
D0
Attempts:
2 left
💡 Hint
Dynamic field names allow you to use a variable as the field name in a struct.
Predict Output
intermediate
2: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);
A20
Bb
C0
DError: Index exceeds matrix dimensions.
Attempts:
2 left
💡 Hint
Each field in 'data' is set to i*10 where i is the loop index.
🔧 Debug
advanced
2: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';
AError because 'record' is not initialized
BError because 'value' is not defined
CNo error, code runs fine
DError because field name must be a string or character vector
Attempts:
2 left
💡 Hint
Field names in structs must be text, not numbers.
📝 Syntax
advanced
2: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'.
Af1 = 'name'; f2 = 'age'; person.f1 = 'Alice'; person.f2 = 30;
Bf1 = 'name'; f2 = 'age'; person.(f1) = 'Alice'; person.(f2) = 30;
Cf1 = 'name'; f2 = 'age'; person{f1} = 'Alice'; person{f2} = 30;
Df1 = 'name'; f2 = 'age'; person.(f1, f2) = {'Alice', 30};
Attempts:
2 left
💡 Hint
Use parentheses and dot notation with a string variable for dynamic field names.
🚀 Application
expert
2: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;
end
A2
B4
C3
D1
Attempts:
2 left
💡 Hint
Struct fields must be unique; repeated field names overwrite previous values.