MATLAB: Create structure names out of cell arrays or strings

stringstructtextscan

Hi everybody
I have a problem to create structure arrays out of strings or cell arrays. Let's say we have a vector A=[1 2 3 4]. I have a string or cell array which reads "This is vector A". I would like to save A in a structure as This.is.vector.A.
The reason is that I have a very large csv or txt file with hundreds of columns, in every column is a header like "This is vector A", and the data of vector A below. I would like to save the data in a structure whose names derive from the string in it's header.
Thanks a lot if anybody could help me!
Best,
Chris

Best Answer

So, if the header is "A stitch in time", then you would want to construct A.stitch.in.time and store A in to that. Except you've just overwritten A and no longer have its value available to store.
Using dynamic variable names is not recommended because of this kind of problem and other problems (the code always gets ugly, and it will usually be broken.)
Using a fixed outer variable name with all parts of the header as field names, would be much more robust and easier to deal with. For example,
indata.A.stitch.in.time
It would probably be easiest to create the nested structure from the end backwards.
hdrwords = regexp(hdr, ' ', 'split');
if isempty(hdrwords); error('empty header string'); end
t = struct(hdrwords{end}, A);
for K = length(hdrwords)-1 : -1 : 2
t = struct(hdrwords{K}, t);
end
indata.(hdrwords{1}) = t;