How to avoid If statement?

조회 수: 7 (최근 30일)
JFz
JFz 2015년 8월 19일
댓글: JFz 2015년 8월 20일
Hi,
I have a few lines of code like this:
if(volTbl.ReturnType(k) == 1)
logR = diff(log(abs(newtable.price)));
else
logR = diff(newtable.price);
end
I would like to avoide the if statement because the tables are large and the calculation is intensive. How to do that? Thanks a lot.
Jennifer
  댓글 수: 2
Image Analyst
Image Analyst 2015년 8월 19일
How large? Like hundreds of millions of elements?
And it's not the "if" that's taking up the time, it's the diff(), and log(). Is this code in a loop over many millions of iterations? Or is it just a one time calculation?
JFz
JFz 2015년 8월 20일
Thanks. yes, you are right. It is indeed in a large for loop.

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

답변 (1개)

Walter Roberson
Walter Roberson 2015년 8월 19일
selectfun = @(cond, tf_funs, x) tf_funs{cond+1}(x);
logR = diff( selectfun(volTbl.ReturnType(k) == 1, {@(x) log(abs(x)), @(x) x}, newtable.price) );
This does not use "if", but I suspect it will be slower than if you used "if".
To get much performance improvement you would need to be writing to a different result location for each "k", such as if the statement were logR(k,:) = ... and you would need a different input location for each, such as newtable(k).price, and you would need to be doing a whole series of "k" values. But when your input is always the same and your output is always the same and you are only doing one "k" value, then it is difficult to get faster than "if".
  댓글 수: 1
JFz
JFz 2015년 8월 20일
Thanks! Let me try it.

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

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by