2014-01-22 75 views
0

V是一個圖像矩陣.D0和D1是二級樹的左右根。 這是一個二叉樹,它有8級。這意味着很多代碼。 ı想使它與遞歸函數。並作爲一個輸出ı需要在數組M的手段的所有根。請任何想法使其遞歸?如何在MATLAB中對二叉樹進行遞歸函數

clear all;clc; 
V=imread('tire.tif'); 
[x y]=size(V); 
U=V*0; 

    M=zeros(1,511); 


    % LEVEL 1 
    M(1,1)=mean(V(:)); 

    % LEVEL 2 
    D0=V(V<=mean(V(:))); % right root for V 
    M(1,2)=mean(D0(:)); 
    D1=V(V>mean(V(:))); %left root for V 
    M(1,3)=mean(D1(:)); 

    % LEVEL 3 
    D00=D0(D0<=mean(D0(:))); %left root for D0 
    M(1,4)=mean(D00(:)); 
    D01=D0(D0>mean(D0(:))); %left root for D0 
    M(1,5)=mean(D01(:)); 

    D10=D1(D1<=mean(D1(:))); %right root for D1 
    M(1,6)=mean(D10(:)); 
    D11=D1(D1>mean(D1(:))); %left root for D1 
    M(1,7)=mean(D11(:)); 

回答

0

我相信這是您正在尋找的解決方案。棘手的部分是跟蹤指數(像往常一樣)。

function M = myrecfun(V, M, n_max, n, i) 
%n: current level (of recursions) 
%i: an integer in [1, 2^(n-1)] 
i_start = 2^n; 
meanV = mean(V(:)); 
if n == 1 
M(1) = meanV 
end 
DR = V(V <= meanV); 
DL = V(V > meanV); 
iR = i_start + 2*i - 2; 
iL = i_start + 2*i - 1; 
M(iR) = mean(DR); 
M(iL) = mean(DL); 
if n < n_max 
M = myrecfun(DR, M, n_max, n+1, iR - i_start + 1); 
M = myrecfun(DL, M, n_max, n+1, iL - i_start + 1); 
else % else of if n < n_max 
M; 
end % end of if n < n_max 
end % of myrecfun 

呼叫的代碼:

n_max = 8; 
V = 100*rand(100,100); %Just my example 
M = zeros(1, 2^(n_max+1)-1); 
Mout = myrecfun(V, M, n_max, 1, 1); 

測試輸出:

總和(MOUT < 50)

ANS =

總和(MOUT> 50)

ANS =

+0

真的感謝有趣我的問題。它給iL的錯誤?未定義的函數或變量'iL'。 (IL)=平均值(DL); 錯誤在==> myrecfun在15 M(iL)=平均值(DL); 錯誤在==> denemerecrsve at 4 Mout = myrecfun(V,M,n_max,1,1); >> @bbarker – 12345

+0

我寫iL = i_start + 2 * i -1;和代碼工作得很好,謝謝你的幫助 – 12345

+0

我認爲它在那裏,但有一個縮進問題:現在修復。 – bbarker