MATLAB: Convert a matrix in a struct

matrixstruct

Hi,
I have a nested struct userTouristicTraj(i).touristicData(j).touristicTraj (attached) and I want to convert it in a matrix. I have used this code:
for i=1:25
for j=1:size(userTouristicTraj(i).touristicData,2)
A(i)=userTouristicTraj(i).touristicData(j).touristicTraj
end
end
but it doesn't do what I want, can you help me? thanks

Best Answer

You haven't attached your data. The following may do what you want:
datasize = numel(userTouristicTraj(1).touristicData);
touristicTraj = zeros(numel(userTouristicTraj), datasize);
for trajidx = 1:numel(userTouristicTraj) %don't hardcode end of loop when you can ask matlab for the actual value
assert(datasize == numel(userTouristicTraj(trajidx).touristicData), 'touristicData size is not consistent');
for dataidx = 1:numel(userTouristicTraj(trajidx).touristicData)
touristicTraj(trajidx, dataidx) = userTouristicTraj(trajidx).touristicData(dataidx).touristicTraj
end
end
Note: I'm not sure why you have size(userTouristicTraj(i).touristicData,2) in your code, which implies that the touristicData field is 2D. Yet you only iterate over one dimension. I have assumed that the field is 1D. I have also assumed that touristicTraj is scalar. And of course, all the touristicData fields must be the same size.
If any of these assumptions are broken, the code above won't work.