How can I make a structure array
Show older comments
Hello everyone,'
I want to make a struct array, or example "Spectra" or "freqs".
How can I implement it on my own (EEG)data?
Thanks in advance for your help.
Neda
Answers (1)
If you pass struct() a cell array of data for a field, then it creates a struct array with the same size() as the size() of the cell array.
%setup to create cell arrays of data
N = 5;
spectras = arrayfun(@(n) randn(10,1), 1:N, 'uniform', 0);
freqs = arrayfun(@(n) sort(randi([0 999], 10, 1)), 1:N, 'uniform', 0);
%now that we have a cell arrays of data we can convert to struct array:
datastruct = struct('Spectra', spectras, 'freqs', freqs);
%verify that the struct is what we expect
whos datastruct
datastruct
datastruct(1).Spectra
spectras{1}
4 Comments
Neda Deljavan
on 24 Jan 2023
Moved: Steven Lord
on 24 Jan 2023
Observe:
%setup to create cell arrays of data
N = 6;
spectras = arrayfun(@(n) randi([-9 9], 10,1), 1:N, 'uniform', 0);
freqs = arrayfun(@(n) sort(randi([0 999], 10, 1)), 1:N, 'uniform', 0);
%now that we have a cell arrays of data we can convert to struct array:
datastruct16 = struct('Spectra', reshape(spectras,1,6), 'freqs', reshape(freqs,1,6));
datastruct23 = struct('Spectra', reshape(spectras,2,3), 'freqs', reshape(freqs,2,3));
whos datastruct16 datastruct23
reshape(spectras,1,6) reshapes the 6-element cell array to be a 1 x 6 cell array. So for datastruct16 we passed in 1 x 6 cell arrays, and we got back a 1 x 6 struct array.
reshape(spectras,2,3) reshapes the 6-element cell array to be a 2 x 3 cell array. So for datastruct23 we passed in 2 x 3 cell arrays, and we got back a 2 x 3 struct array.
Neda Deljavan
on 25 Jan 2023
Walter Roberson
on 26 Jan 2023
t1 = cellfun(@squeeze, num2cell(spectra, 2), 'uniform', 0);
t2 = num2cell(freqs);
output = struct('spectra', t1(:) , 'freqs', t2(:) );
Categories
Find more on Data Types 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!