2013-02-14 124 views
2

我知道它可能在Java和C++等,但這是可能的Matlab? 我最近發現Matlab沒有像value++這樣的快捷方式,他們不得不使用value = value+1,所以我想知道它是否有可能將此函數轉換爲迭代函數。我不知道從哪裏開始。如果是這樣,它是否比遞歸函數更有益?Matlab - 將遞歸函數轉換爲迭代函數

function [lines] = recurse(R,C, lines, T_l, count, directions) 
    [rows, columns] = size(lines); 
    if((R < 2 || C < 2) || (R > rows-1 || C > columns - 1) || count>500) 
     count= count+1; 
     return; 
    end 
    count= count+1; 
    direction = directions(R,C); 
      if(direction >= 68 || direction <=-68)           
       if(lines(R-1,C) > T_l) 
        lines(R-1,C) = 0; 
        lines = recurse(R-1,C, lines, T_l, count, directions); 
       end 
       if(lines(R+1,C) > T_l) 
        lines(R+1,C) = 0; 
        lines = recurse(R+1,C, lines, T_l, count, directions); 
       end 
      elseif (direction <= -23 && direction >-68)          
       if(lines(R+1,C+1) > T_l) 
        lines(R+1,C+1) = 0; 
        lines = recurse(R+1,C+1, lines, T_l, count, directions); 
       end 
       if(lines(R-1,C-1) > T_l) 
        lines(R-1,C-1) = 0; 
        lines = recurse(R-1,C-1, lines, T_l, count, directions); 
       end 
      elseif (direction >= 23 && direction < 68)          
       if(lines(R+1,C-1) > T_l) 
        lines(R+1,C-1) = 0; 
        lines = recurse(R+1,C-1, lines, T_l, count, directions); 
       end 
       if(lines(R-1,C+1) > T_l) 
        lines(R-1,C+1) = 0;              
        lines = recurse(R-1,C+1, lines, T_l, count, directions); 
       end 
      else                    
       if(lines(R,C+1) > T_l) 
        lines(R,C+1) = 0;               
        lines = recurse(R,C+1, lines, T_l, count, directions); 
       end 
       if(lines(R,C-1) > T_l) 
        lines(R,C-1) = 0; 
        lines = recurse(R,C-1, lines, T_l, count, directions); 
       end 
      end 
    lines(R,C) = 255; 
    return; 

基本上,我目前有一個函數遞歸調用第二個函數。我希望將這個遞歸函數合併到函數中,將其作爲一組迭代命令調用它。 我很確定它會變慢,但速度對我來說不是問題,我很想看看這些循環是如何工作的。謝謝。

+1

1. **這是可能的Matlab?**是的,它是。 2. **如果是這樣,它是否比遞歸函數更有益?**不,它不是。這是一個折衷。迭代與遞歸是相當多的算法,幾乎與語言無關。迭代通常會更復雜一些,更難以理解,但是在堆棧框架設置等方面開銷較少,甚至可能需要更少的內存(雖然這並非總是如此)。 – thang 2013-02-14 23:52:08

+1

將遞歸函數轉換爲迭代函數的一種方法是識別堆棧中存儲的內容。看看它有多少是絕對必要的。無論什麼必要,創建一個堆棧式結構來存儲它,然後在該結構上進行操作。 – thang 2013-02-14 23:54:48

回答

1

您可以使用operator完成value++(儘管如此,您仍然需要符號工具箱)。

operator(symb, f, T, prio)定義了一個T(前綴|後綴|二進制)類型的新運算符符號symb,其優先級爲prio。函數f使用new運算符來計算表達式。

鑑於運算符號「++」,也就是說,與評價函數f,以下表達式是由解析器建立,這取決於操作者,其中的類型:

前綴:輸入+ + x導致f(x)。

Postfix:在f(x)中輸入x ++結果。

Binary:輸入x ++ y ++ z導致f(f(x,y),z)。

Nary:輸入x ++ y ++ z結果爲f(x,y,z))。

查看更多matlab的documentation