Concatenation of variables inside a struct

2 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2019-5-4
编辑:Stephen23 2019-5-4
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 个评论
Stephen23
Stephen23 2019-5-4
编辑:Stephen23 2019-5-4
"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.
Albert
Albert 2019-5-4
With this simple modification the code works magically perfect! Excellent!
many many thanks

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by