Concatenation of variables inside a struct

8 views (last 30 days)
Albert
Albert on 4 May 2019
Commented: Albert on 4 May 2019
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

Accepted Answer

Stephen
Stephen on 4 May 2019
Edited: Stephen 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
Albert
Albert on 4 May 2019
With this simple modification the code works magically perfect! Excellent!
many many thanks

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by