Concatenation of variables inside a struct
9 views (last 30 days)
Show older comments
Hi,
I have an array of structs with two fields on the struct. So for each element of the array I have:
% str is an array of structs
str(1).latlon = [10 20 30 40;3 4 5 6].'; % latlon is a X x 2 matrix, X is variable for each str array index
str(1).val = 200; % val is always a scalar
str(2).latlon = [50 60;3 4].';
str(2).val = 234;
latlon_all = cat(1,str.latlon);
I can concat all the latlon matrices easily with the instruction above. The problem is that I want to concat the val field in the struct with the number of rows in the latlon matrix. As a result, I would like a variable val_all to be:
val_all = [200 200 200 200 234 234];
programatically. The idea is to create the variable val_all in one shot after all the elements of the str array have been created, similarly to what it is done with latlon_all. Of course I could make loops or could modify the way the variable val is set for each element in the array during assignment, but with this situation, is there a way to do the concatenation taking into account the number of rows in the latlon matrix?
Thanks very much
0 Comments
Accepted Answer
Stephen23
on 4 May 2019
Edited: Stephen23
on 4 May 2019
Method one: size and repelem:
>> cnt = arrayfun(@(s)size(s.latlon,1),str);
>> out = repelem(cat(1,str.val),cnt)
out =
200
200
200
200
234
234
Method two: repmat and cell2mat:
>> fun = @(s)repmat(s.val,size(s.latlon,1),1);
>> out = cell2mat(arrayfun(fun,str(:),'uni',0))
out =
200
200
200
200
234
234
More Answers (0)
See Also
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!