Speeding up for loop with if statement

조회 수: 6 (최근 30일)
Josh Parks
Josh Parks 2020년 3월 23일
댓글: Josh Parks 2020년 3월 23일
Hi all,
Got what I believe is a noob question here: I have a function and it seems that 90% of my runtime is taken up by one loop. I'm wonderin if you guys can help me bring that down/out
The code is as follows (I've replaced the actually O and gamma variables with rands)
Note I originally wrote this with a lot of for loops as I was going to translate it to C and wanted the proting to be straight forward, but now I have this huge bottlneck (I would still prefer to solve it in a way that translates easily to C --- when I get time to port the project :P).
N = 4;
T = 3000000;
M = 170;
O = randi(M,1,T);
gamma = rand(N,T);
B = zeros(N,M);
for j = 1:N
denom = 0;
for t = 1:T
denom = denom + gamma(j,t);
end %t
for k = 1:M
numer = 0;
for t = 1:T
if(O(t) == k)
numer = numer + gamma(j,t);
end
end %t
B(j,k) = numer/denom;
end %k
end %i
  댓글 수: 2
Walter Roberson
Walter Roberson 2020년 3월 23일
accumarray(). You could probably do all of numer calculations at the same time. denom = sum(gamma, 2) in vectorized form
Josh Parks
Josh Parks 2020년 3월 23일
Thanks, in case anyone was wondering about the solution:
denom = sum(gamma,2);
for j = 1:N
numerB = accumarray(O',gamma(j,:)',[M 1],@sum)';
B(j,:) = numerB./denom(j);
end %i

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by