Preallocating a structure with a changing number of rows within a field

조회 수: 4 (최근 30일)
Hi all. I'm relatively new in MATLAB and I'm trying to optimize my code.
I have this function:
function G = GroupM1(A,num_K)
%Grouping r according to m1 and arranging from high to low
for i = [1:num_K]
G(i).dist = A(A.m1 == i,:);
G(i).dist = sortrows(G(i).dist, string(i),'ascend');
end
end
It produces a structure 'G' (see attached file)
'A' is just a 100x17 table. And In this case, num_K == 9. The number of rows in structure 'G' is always equal to num_K.
My questions is:
How can I preallocate this structure 'G' that has 1 field (.dist) containing different sized tables so that the row number is always equal to num_K?
Any help is appreciated. Thank you.

채택된 답변

Bruno Luong
Bruno Luong 2021년 1월 9일
There is no need to preallocate a field (or in fact any variable) if you don't grow the array itself in a loop, which is your case.
  댓글 수: 2
Christoper Angelo Malayan
Christoper Angelo Malayan 2021년 1월 10일
Hi Bruno. Thanks for answering.
But the table sizes within the fixed structure 'G' is changing and MATLAB advices me to preallocate it i.e. the rows of struct G.dist is always == to num_K but the dimension of the table G(n).dist will change every iteration.
Any tips on how to preallocate these tables within the struct?
Thanks
Bruno Luong
Bruno Luong 2021년 1월 10일
I though you want to prealloacate the fields.
If you want to preallocate the structure array G do this before the loop
G = struct('dist',cell(1,num_K));

댓글을 달려면 로그인하십시오.

추가 답변 (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