In: Computer Science
Write a function using MATLAB that will accept a structure as an argument and return two cell arrays containing the names of the fields of that structure and the data types of each field. Be sure to check that the input argument is a structure, and generate an error message if it is not.
ANSWER:--
GIVEN THAT:--
MATLAB Code::--
function [ returnObj ] = getStructData( structobj
)
if isstruct(structobj)~=1%checking if input is not a
structure
error('Not a structure')%throwing error
else
%getting the field names
fields = fieldnames(structobj);
%creating cell artay for datatypes
dataTypes = cell(size(fields));
index=1;
for i = 1:size(fields)
%getting the datatype of every field and storing at the proper
index
dataTypes{index} = class(getfield(structobj,fields{i}));
index=index+1;
end
%storing field name and datatype in a return object
returnObj = [fields,dataTypes];
end
end
Sample Output:--
>> patient = struct('name', 'John Doe','billing', 127)
patient =
name: 'John Doe'
billing: 127
>> getStructData(patient)
ans =
'name' 'char'
'billing' 'double'
METHOD -2 :--
clear all
clc
s(1)=struct('e',1,'re',[3,2],'st','re');
s(2)=struct('e',4,'re',[3,2],'st','re');
[c1,c2]=structcell(s)
function [c1,c2]=structcell(s)
c1=fieldnames(s)';
c2={};
C=struct2cell(s);
for i=1:length(c1)
c2{i}=class(C{i});
end
end