How to make this simple script faster?
2 次查看(过去 30 天)
显示 更早的评论
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).
采纳的回答
Image Analyst
2020-2-3
编辑:Image Analyst
2020-2-3
Does this work:
X = zeros(10000000, 1);
a = 1;
b = length(Sta);
lastIndex = 0
for i = a:b
if isfield(Sta{i}, 'test')
t = Sta{i}.test;
lt = length(t);
X(lastIndex+1:lastIndex+lt) = t;
lastIndex = lastIndex + lt;
end
end
X = X(1:lastIndex);
What is the size of Sta? How many elements does it have?
3 个评论
Image Analyst
2020-2-3
编辑:Image Analyst
2020-2-3
It might be. I experimented with doing things like (:) and {:} and putting stuff in brackets and using vertcat() but I just couldn't find the exact syntax that would do it. You'd have to experiment around some.
Can you store them in a more convenient way in the first place?
更多回答(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));
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!