Better way to keep dimensions using reshape from extracted struct array?
Show older comments
HEllo
I am wondering what is the best way to extract the data from an structured array in matlab and keeping is dimensionality if I use reshape while processing it.
Let's say I have the following struct array
load('data.mat')
myData.data.b
In order to extract all b values I would do
[myData.data(:).b]
But this rises the issue that the dimensionality of b is lost, since now it is treated as an vector. If I do reshape to try to recover that dimensionality I will get
bb=reshape([myData.data(:).b]',[],2)
which is still not the original data, because all even row are swapped compared to original. So the only thing I came up was to undo that swapping on even rows via
bb(2:2:end,:) = fliplr(bb(2:2:end,:))
Hence I wonder whether there exists a better way to extract b from the struct array without having to do the reshape + even elemen flip.
thanks in advance,
Bes regards
7 Comments
@Javier Cuadros, you can try using a loop to extract data from nested struct array
load('data.mat')
for k = 1:numel(myData.data(:))
mD(k,:) = myData.data(k).b;
end
mD
Javier Cuadros
on 20 Aug 2024
Stephen23
on 20 Aug 2024
Why not just use VERTCAT as Voss shows?
VBBV
on 20 Aug 2024
@Javier Cuadros,, Do you mean data size of field b is not constant ? if it has homogenous size, then as @Voss . @Stephen23 mentioned its better to use vertcat function
Javier Cuadros
on 20 Aug 2024
Javier Cuadros
on 20 Aug 2024
Stephen23
on 20 Aug 2024
"I didn't know that I could use it in that way!"
You can use comma-separated lists with any function.
Accepted Answer
More Answers (1)
arushi
on 20 Aug 2024
Hi Javier,
To extract data from a structured array in MATLAB while preserving its original dimensionality, you can use a combination of array manipulation functions that maintain the structure of your data. In your case, since each element of myData.data(:).b is a 1x2 vector, you can use reshape and cell2mat in a way that respects the original organization of the data.
Here’s a more efficient approach to extract b values from the struct array without manually flipping rows:
- Extract Data into a Cell Array: Use arrayfun to extract the data into a cell array, preserving the structure.
- Convert to a Matrix: Use cell2mat to convert the cell array into a matrix.
bMatrix = cell2mat(bCellArray');
bOriginal = reshape(bMatrix, [], 2);
Hope this helps.
1 Comment
Categories
Find more on Multidimensional Arrays 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!