How to make this simple script faster?
이전 댓글 표시
Each of the Sta{i}.test is a one-column data with unknown number of rows. As you know, to keep expanding Variable X is not the most efficient way of doing this.
Is there a way I can get my X values faster without writing a loop?
X = [];
for i = a:b
if isfield(Sta{i}, 'test')
X = [X; Sta{i}.test];
end
end
Many thanks!
댓글 수: 1
Image Analyst
2020년 2월 3일
편집: Image Analyst
2020년 2월 3일
Are you saying that sometimes the structure inside the cell might not have a field called "test"? What if you just allocated X as, say, 10 million elements or way more than you ever expect to have, then crop to the proper length after the loop. See my Answer below (scroll down).
채택된 답변
추가 답변 (1개)
David Hill
2020년 2월 3일
You could preallocate X with nan to the largest expected and then delete the excess nan's at the end.
X = nan(10000000,1);
count=1;
for i = a:b
if isfield(Sta{i}, 'test')
temp=count+length(Sta{i}.test);
X(count:temp-1) = Sta{i}.test;
count=temp;
end
end
X=X(~isnan(X));
카테고리
도움말 센터 및 File Exchange에서 System-Level Simulation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!