How do I generate a vector of ordered integer without a loop or in faster way

I have to generate a vector 0123123451234567123456789 and the quickest idea was given by cyclist
M=[0];
for q=3:2:9
M=[M,1:q];
end
which is very slow. Does anyone have idea to make it faster? Thanks alot

回答 (2 件)

dpb
dpb 2015 年 11 月 25 日
Prealllocate and populate instead of concatenating for starters...
M=zeros(1,1+sum(q));
i1=2;
for q=3:2:9
i2=i1-1+q;
M(i1:i2)=[1:q];
i1=i2+1;
end
I gotta' run at the moment but a kreative use of
doc kron % _might_ bring nirvana, not sure otomh; haven't had time to think it thru...

3 件のコメント

Oluwaseun Lijoka
Oluwaseun Lijoka 2015 年 11 月 25 日
Thanks alot but is it possible to do away with for loop in this case or it is never avoidable?
Oluwaseun Lijoka
Oluwaseun Lijoka 2015 年 11 月 25 日
I also think matlab will complain about the first line M=zeros(1,1+sum(q)); where q is not defined.
dpb
dpb 2015 年 11 月 25 日
Well, you have to define the range, yes...

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

Stephen23
Stephen23 2015 年 11 月 25 日
編集済み: Stephen23 2015 年 11 月 25 日
You can adapt my answer to your other question:
X = floor(sqrt(0:(p+1)^2-1));
Y = diff(X);
Y(logical(Y)) = 0:-2:-2*nnz(Y)+1;
Y(Y==0) = 1;
Z = [0,cumsum(Y)];
This is hundreds of times faster than your original code (p=10000):
Elapsed time is 3.095720 seconds.
Elapsed time is 0.000041 seconds.
Note that as p gets larger it will reach your memory limit very quickly: each magnitude increase in p causes a two-magnitude increase in the number of elements of the output vector.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 11 月 25 日

コメント済み:

dpb
2015 年 11 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by