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
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
Image Analyst 2020 年 2 月 3 日
編集済み: Image Analyst 2020 年 2 月 3 日

0 投票

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 件のコメント

Leon
Leon 2020 年 2 月 3 日
There are dozens of elements for each Sta. The size is on the thousands.
One question, if test is always available. Is it possible to do things like this without writing a loop? For example, is there something like this within Matlab?
Sta([a:b]).test
Similar to
Data([a:b],5);
Image Analyst
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?
Leon
Leon 2020 年 2 月 3 日
Any recommendation on what's the best way to store them in order to access them in the most convenient way?
In a matrix named A like this:
Sta#, Var1, Var2
1 35 127
1 21 256
1 11 222
2 15 188
2 12 236
3 27 333
4 35 467
5 11 222
5 23 376
Then how do I quickly get all the rows with a Sta# between 2 and 4, for example?
Ind = A(:,1)>=2 & A(:,1)<=4;
B = A(Ind, :);
Is there a better setup? Many thanks!

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2020 年 2 月 3 日

0 投票

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));

1 件のコメント

Leon
Leon 2020 年 2 月 3 日
Many thanks for the solution, David! So bad I can only accept one answer.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

リリース

R2019b

タグ

質問済み:

2020 年 2 月 2 日

コメント済み:

2020 年 2 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by