Quickest way for alternate indexing a vector
7 次查看(过去 30 天)
显示 更早的评论
Hey,
I am looking for the quickest way to create a vector like this :
u = [5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55]
In which steps 2 and 4 alternate as you can see.
At the moment I manage to do it like this for instance :
u = 1+cumsum(repmat([4 2],[1 9]))
Where n is a given limit value. But this is too slow to me.
Would you know a way to get the same result but quicker ? Perhaps using only Matlab semi colon operator and / or basic math (+,*) operations ? EDIT : especially when u has a lot of elements.
Thank you.
Cheers,
Nicolas
2 个评论
Mathieu NOE
2023-12-21
hello
IMHO this seems not very slow
n = 1e6;
tic
u = 1+cumsum(repmat([4 2],[1 floor(n/6)]));
toc
size(u)
采纳的回答
Stephen23
2023-12-21
u = [5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55]
v = 5:2:55;
v(3:3:end) = []
4 个评论
更多回答(4 个)
Bruno Luong
2023-12-21
编辑:Bruno Luong
2023-12-21
Try to do something clever (1st and 2nd methods) but it is slower than your code 53rd method). A small modificationof your code seems to be the most efficient (last method)
test
function test
n=1000000; % array length
tic
u=(5:3:(n-1)*3+5)-mod(0:n-1,2);
toc % Elapsed time is 0.010612 seconds.
tic
u=0:n-1;
u=5+3*u-mod(u,2);
toc % Elapsed time is 0.009249 seconds.
tic % Your method
u = 1+cumsum(repmat([4 2],[1 n/2]));
toc % Elapsed time is 0.002047 seconds.
tic % sligh modification method
u = repmat([4 2],[1 n/2]);
u(1)=5;
u = cumsum(u);
toc % Elapsed time is 0.001861 seconds.
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!