Concatenation of variables inside a struct
2 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
3 Comments
Stephen23
on 4 May 2019
Edited: Stephen23
on 4 May 2019
"In this case the code you proposed fails."
The first method is very easy to adapt for zero-row arrays (note the cnt>0 logical index):
>> out = repelem(cat(1,str.val),cnt(cnt>0))
out =
200
200
200
200
234
234
As an aside, I do not see any good reason why repelem should not accept zero replications. Seems rather inconsistent to me, as zero-length vectors are perfectly reasonable and MATLAB normally handles them without complaint.
More Answers (0)
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!