V是图像矩阵.D0和D1是级别1的二叉树的左右根。 这是一个二叉树,它有8级。这意味着很多代码。我想用递归函数来实现它。作为一个输出,我需要数组M中所有的平均值。请不要让它递归?
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 :(得分: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 =
256
总和(Mout> 50)
ans =
255