Which method to use, basic for loop or loop through values of a vector
12 次查看(过去 30 天)
显示 更早的评论
Vector ind has indices I want to loop through, x has values.
ind = [1 3 5];
x = [10 20 30 40 50 60 70];
ind_len = size(ind,2)
Approach 1: When using a for loop, should I use the basic incremental for loop, where I access each element of x with index values from ind vector
for i = 1:ind_len
x(ind(i))
end
Approach 2: Don't use ind_len length variable and assign ind vector to for loop
for i = ind
x(i)
end
Which method is efficient ?
0 个评论
采纳的回答
Jan
2020-12-24
x = rand(1, 1e6);
y = zeros(size(x));
ind = randperm(numel(x));
tic
for loop = 1:10
for k = 1:numel(ind)
y(ind(k)) = x(ind(k));
end
end
toc
tic
for loop = 1:10
for k = ind
y(k) = x(k);
end
end
toc
% Elapsed time is 0.395765 seconds.
% Elapsed time is 0.739708 seconds.
The first approach can be handled more efficiently.
2 个评论
更多回答(1 个)
KALYAN ACHARJYA
2020-12-24
编辑:KALYAN ACHARJYA
2020-12-24
More simpler, without loop
x(ind)
The 2nd approach (If I must have to choose one from above)
2 个评论
KALYAN ACHARJYA
2020-12-24
编辑:KALYAN ACHARJYA
2020-12-24
Great one, once I run the code, as given in the question..
ind = [1 3 5];
x = [10 20 30 40 50 60 70];
ind_len = size(ind,2);
tic
for i = 1:ind_len
x(ind(i));
end
toc
tic
for i = ind
x(i);
end
toc
Elapsed time is 0.000021 seconds.
Elapsed time is 0.000016 seconds.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!