2

任何人对比下面的 if else 功能更有效的解决方案有想法吗?这需要代码的大部分时间,所以我需要减少它。

完整的功能是

     function result = vre(t,r,e,n,d)
         if (e==4 && r>0)
        result = 0;
    elseif (e==4 && r==0)
        result = 1;
    elseif (e<4 && r==1)
        result = t;
    elseif (e<4 && r==2)
        result = d;            
    else
        result=n;
    end
end
4

3 回答 3

5

If this function is taking most of your processing time, it is almost certainly because you're calling it too many times. In turn, this is likely because you are calling it on each element of a vector or matrix individually. I suggest changing the function to accept matrix inputs for e and r, so you can perform all the checks at once - matlab is built for matrix operations, so taking advantage of those is always a good idea.

function result = vre(t,r,e,n,d)
#% add error checking for size of input args if desired
result = ones(size(e))*n; #% default result; next assign special cases
result(e==4 & r>0) = 0; #% note the single & for element-wise 'and'
result(e==4 & r==0) = 1;
result(e<4 & r==1) = t;
result(e<4 & r==2) = d;

end

The function now returns a matrix that is the same size as the input matrices - for single elements it will work exactly the same as your current version, but for higher dimensional inputs it will work too, and probably give you a substantial speed boost.

于 2013-03-29T03:06:42.440 回答
4
function result = vre(t,r,e,n,d)
     if (e==4) {
         if(r>0)
             result = 0;
         elseif (r==0)
             result = 1;
     }
     elseif (e<4) {
          if(r==1)
              result = t;
          elseif (r==2)
              result = d; 
     }           
    else
        result=n;
    end
end

通过这种方式,您将只验证 (e==4) 和 (e<4) 一次,避免不必要的验证。

希望它能节省一些处理时间。

PS:没有测试,因为我没有安装 MatLab。

于 2013-03-29T02:55:08.633 回答
2

Try this:

function result = vre(t,r,e,n,d)
  if (e==4)
    result = (r==0);
  elseif (e<4)
    result = (r==1)*t+(r==2)*d;
  else
    result=n;
  end
end

I can't guarantee that it's more efficient (I use octave rather than matlab, so speed testing isn't going to help). But I think it will be.

于 2013-03-29T03:10:55.687 回答