Consider the following MATLAB code:
students(1).name = 'Alice';
students(1).age = 21;
students(2).name = 'Bob';
students(2).age = 22;
result = {students.name};What is the value of result after running this code?
students(1).name = 'Alice'; students(1).age = 21; students(2).name = 'Bob'; students(2).age = 22; result = {students.name};
Remember that curly braces {} create cell arrays in MATLAB.
Using {students.name} collects the name fields from each element of the structure array into a cell array. So result is a 1x2 cell array containing 'Alice' and 'Bob'.
Given this MATLAB code:
data(3).value = 0; data(1).value = 10; data(2).value = 20;
What is the size of data after these assignments?
data(3).value = 0; data(1).value = 10; data(2).value = 20;
Assigning to data(3) creates elements 1 to 3 in a row vector by default.
In MATLAB, assigning to data(3) creates a 1x3 structure array. The default shape is a row vector unless specified otherwise.
Examine this MATLAB code:
info(1).name = 'John';
info(2).age = 30;
names = {info.name};What error will occur when running this code?
info(1).name = 'John'; info(2).age = 30; names = {info.name};
Check if all elements of the structure array have the field name.
Because info(2) does not have the field name, trying to access info.name causes an error.
You have a structure array records with 5 elements. You want to add a new field status with value 'active' to every element. Which code does this correctly?
Think about how MATLAB assigns fields to structure arrays element-wise.
Only option B assigns the new field status to each element individually. Option B creates a single field for the whole array, which is invalid. Options C and D are syntactically incorrect.
Consider this MATLAB code:
team(1).player.name = 'Anna'; team(1).player.score = 10; team(2).player.name = 'Ben'; team(2).player.score = 15; scores = [team.player.score];
What is the value of scores after running this code?
team(1).player.name = 'Anna'; team(1).player.score = 10; team(2).player.name = 'Ben'; team(2).player.score = 15; scores = [team.player.score];
Accessing nested fields in structure arrays returns arrays of those values.
Accessing team.player.score collects the score fields from each nested player structure into a numeric array. So scores is [10 15].