You are supposed to create a function using MATLAB that does whatis described be
ID: 3613856 • Letter: Y
Question
You are supposed to create a function using MATLAB that does whatis described below. I know that there are no MATLAB books in thissite already, I just thought someone might be able to help.Thanks!
Function Name: cellFromStruct
Inputs:
1: (struct) - a single structure
Outputs:
1: (cell) - a cell array in the format requiredfor struct();
Function Description:
This function takes an input of a structure
and outputs a cell array representing that structure. Thecell
array should have the form:
ca = {'fieldname1',value1,'fieldname2',value2,...}
This is very similar to the syntax of the struct()function.
HINT: Remember the fieldnames() function.
Test Case 1:
s1 = struct('make','Ford','Model','Explorer');
ca1 = cellFromStruct(s1);
ca1 -> {'make','Ford','Model','Explorer'}
Test Case 2:
s2.firstname = 'George';
s2.lastname = 'Burdell';
ca2 = cellFromStruct(s2);
ca2 -> {'firstname','George','lastname','Burdell'}
Test Case 3:
s3 = struct([]); % Empty structure
ca3 = cellFromStruct(s3);
ca3 -> {}
Explanation / Answer
function cell= cellFromStruct(p)
%checks to see if p is an empty structure
ifisempty(p)
cell=struct2cell(p);
% seperates the field names of p and creates a new cell arrray
else
z=fieldnames(p);
a=z{1};
b=z{2};
c=getfield(p, a);
d=getfield(p, b);
cell={a c b d};
end
The only thing I know is wrong with my codeis, it only works with 2 fields and one value in each of thosefields.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.