Convert cell array of structures to numeric vector
3 views (last 30 days)
Show older comments
Suppose I have
ale{1}.a = 0;
ale{2}.a = 1;
ale{3}.a = 1.5
ale_vec = NaN(length(ale),1);
for ii=1:length(ale)
ale_vec(ii) = ale{ii}.a;
end
disp(ale_vec)
I would like to generate
%ale_vec = [0,1,1.5]
Is there a quick way to do this without using a loop?
Thanks!
0 Comments
Accepted Answer
Yukthi S
on 3 Oct 2024
The function arrayfun can be used to extract the values of the field a from each structure within the cell array ale and store them in a vector called ale_vec without explicitly using a for loop.
ale{1}.a = 0;
ale{2}.a = 1;
ale{3}.a = 1.5;
% Use arrayfun to extract the 'a' field from each element in the cell array
ale_vec = arrayfun(@(x) x.a, [ale{:}]);
% Display the result
disp(ale_vec);
You can find more about arrayfun in the below MathWorks documentation:
1 Comment
Voss
on 3 Oct 2024
@Alessandro: I thought you wanted to know a quick way without a loop, but the answer you've accepted uses arrayfun, which uses a loop and is slower than the "direct" method I showed, which uses only indexing and concatenation:
N = 7;
ty = zeros(N,1);
tv = zeros(N,1);
M = 10.^(0:N-1).';
for ii = 1:N
ale = num2cell(struct('a',num2cell(rand(1,M(ii)))));
ty(ii) = timeit(@()run_arrayfun(ale));
tv(ii) = timeit(@()run_direct(ale));
end
format long g
T = table(M,ty,tv,'VariableNames',{'# of cells','arrayfun time','direct time'})
function V = run_arrayfun(C)
V = arrayfun(@(x) x.a, [C{:}]);
end
function V = run_direct(C)
S = [C{:}];
V = [S.a];
end
More Answers (1)
Voss
on 3 Oct 2024
ale{1}.a = 0;
ale{2}.a = 1;
ale{3}.a = 1.5
This will work for the given example:
S = [ale{:}];
ale_vec = [S.a]
1 Comment
Voss
on 3 Oct 2024
If the structs inside the cells of the cell array have different sets of fields, then they cannot be put together into a single struct array (which is what [ale{:}] does). In that case, you can use cellfun which (like arrayfun) implements a loop:
% cell array containing structs with different field sets
ale{1}.a = 0;
ale{2}.a = 1;
ale{3}.a = 1.5;
ale{3}.b = -2;
ale{:}
ale_vec = cellfun(@(s)s.a,ale)
See Also
Categories
Find more on Structures 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!