Convert cell array of structures to numeric vector
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!
Accepted Answer
More Answers (1)
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
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)
Categories
Find more on Loops and Conditional Statements 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!