Which method to use, basic for loop or loop through values of a vector

조회 수: 5 (최근 30일)
Thrisha R
Thrisha R 2020년 12월 24일
편집: KALYAN ACHARJYA 2020년 12월 24일
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 ?

채택된 답변

Jan
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.

추가 답변 (1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 12월 24일
편집: KALYAN ACHARJYA 2020년 12월 24일
More simpler, without loop
x(ind)
More, How to measure the performance of the code, link
The 2nd approach (If I must have to choose one from above)
  댓글 수: 2
Thrisha R
Thrisha R 2020년 12월 24일
Thank you for your time, I agree with your answer in printing it as such. But I intend to do other operation other than printing.
I measured the time for each of the for loops, the first approach turned out to be faster.
Elapsed time for first approach is 0.001047 seconds.
Elapsed time for second approach is 0.001211 seconds.
KALYAN ACHARJYA
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by