필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Indexing on array !

조회 수: 1 (최근 30일)
Sonima
Sonima 2019년 2월 2일
마감: MATLAB Answer Bot 2021년 8월 20일
Hello!
I have an array (a) which has 1M values. Array (b) should be calculated based on array (a) and last value in b.
b(20)= max(a(1:20));
for i=21:length(a)
b(i) = b(i-1) + a(i);
end
Is it possible to calculate the "b" without loop with indexing? something like:
b(21:length(a)) = b(20:length(a)-1) + a(21:length(a));
Thanks.

답변 (1개)

Image Analyst
Image Analyst 2019년 2월 2일
편집: Image Analyst 2019년 2월 2일
What do you want b(1:19) to be?
You could set up the indexes in advance, but it will take about 3 to 4 times as long to do the vectorized way (for a million elements) as the loop way.
a = rand(1, 1000000);
b = a; % Initialize b to be same length as a.
% Method 1: vectorized:
% Assign indexes to do a vectorized loop
tic
% Assign the twentieth element (ONLY) of b.
b(20)= max(a(1:20));
indexes = 21:length(a);
b = b(indexes - 1) + a(indexes);
toc
% Method 2 for loop:
tic
% Assign the twentieth element (ONLY) of b.
b(20)= max(a(1:20));
for i=21:length(a)
b(i) = b(i-1) + a(i);
end
toc
Results:
Elapsed time is 0.043703 seconds.
Elapsed time is 0.011023 seconds.

이 질문은 마감되었습니다.

태그

Community Treasure Hunt

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

Start Hunting!

Translated by