need help with dynamic field expression

1 view (last 30 days)
Kelly
Kelly on 5 Oct 2015
Commented: Kelly on 6 Oct 2015
The assignment is that we are given a structure with two unknown fields, one is a cell array inside of which is stored a string, the other is not a cell array. The function fixArray should keep the field with the cell in it (don't do anything to it) but remove the other field that is not a cell array. Then, replace the removed field with a new field that is named as the string inside the cell array. To the new field, the string "it's working!" should be assigned. Output the final structure.
I was trying to use dynamic field expression when creating the new structure but it doesn't seem to be working. please help!!!
function[new_structure] = fixArray(old_structure)
flds= fieldnames(old_structure);
a= old_structure.(flds{1});
b= old_structure.(flds{2});
A= iscell(a);
B= iscell(b);
new_structure = struct;
if A==1
new_structure = struct(flds{1}, a);
new_structure = rmfield(old_structure, flds{2});
new_structure = struct(a, 'It works!');
end
if A==0
new_structure = struct(flds{2}, b);
new_structure = rmfield(old_structure, flds{1});
new_structure = struct(a, 'It works!');
end
end

Answers (1)

Walter Roberson
Walter Roberson on 5 Oct 2015
Your code has
new_structure = struct(flds{1}, a);
new_structure = rmfield(old_structure, flds{2});
new_structure = struct(a, 'It works!');
which creates new_structure and then twice overwrites it with a completely different value. The effect is as if you had only executed the last of those three lines.
  3 Comments
Walter Roberson
Walter Roberson on 5 Oct 2015
If A==1 then iscell(a) is true, and you would be trying to use the cell array a instead of the string stored in the cell array. a{1} to get to the content of the first element of a.
Kelly
Kelly on 6 Oct 2015
Awesome, I got it! Thank you!

Sign in to comment.

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!