필터 지우기
필터 지우기

Concatenation of variables inside a struct

조회 수: 3 (최근 30일)
Albert
Albert 2019년 5월 4일
댓글: Albert 2019년 5월 4일
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에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by