繁体   English   中英

在Matlab上用一个输入和两个输出来迭代函数的问题

[英]Trouble iterating a function with one input and two outputs on Matlab

我创建了一个函数(命名为MyFunction),给定矩阵A,该函数输出两个矩阵B和C,即[BC] = MyFunction(A)。

我正在尝试创建另一个函数,给定矩阵A时,将计算MyFunction(A),然后计算MyFunction(B)= [DE],然后计算MyFunction(C)= [FG],然后计算MyFunction(D) ,MyFunction(E),MyFunction(F)和MyFunction(G)等,直到输出的矩阵开始重复。 我知道这个过程一定会终止。

我真的很难构造这段代码。 任何建议将不胜感激。

我认为您要尝试的是二叉树递归。 在不了解更多问题的情况下,尤其是在不知道要作为此过程的输出结果的情况下,很难给出好的解决方案。

我对此进行了举例说明,以举例说明您如何执行此操作。 它不一定是最有效的,因为它存储了每一步的所有结果。 给定输入矩阵A,它会计算2输出函数[B, C] = MyFunction(A)并查找isequal(A, B)isequal(A, C) 发生这种情况时,它将输出该点的树的深度,即在重复之前必须进行多少次迭代。 带有全局变量的位只是为了让我可以用一个简单的固定点做一个简单的例子(第k个迭代只是A ^ k)。 最多将重复10次。

function depth = myRecursor(A)

global A_orig;
A_orig = A;

depth = 1;
max_depth = 10;

pvs_level = cell(1);
pvs_level{1} = A;


while depth < max_depth,
    this_level = cell(2*length(pvs_level), 1);     
    for ix = 1 : length(pvs_level),
        [B, C] = MyFunction(pvs_level{ix})
        if isequal(B, A) || isequal(C, A),
            return;
        end
        this_level{2*ix - 1} = B;
        this_level{2*ix} = C;
    end
    depth = depth + 1;
    pvs_level = this_level;
end

function [B, C] = MyFunction(A)

global A_orig;

B = A_orig*A;
C = 2*A;

因此,例如myRecursor(eye(2))给出1(duh),而myRecursor([0 1; 1 0])得到2。

我认为您应该使用单元格:

function [B]=Myfunction(A)
  B=cell(1,numel(A)*2);
  for n=1:numel(A)
    B{n}=func1(A{n}) %%% put some processing here
    B{numel(A)+n}=func2(A{n})  %%% put some other processing here
  end
end

编辑:改写错误的算法

function [list] = newFunction(A)   % returns all matrix generated matrix

list{1}=A;

done=0;
ii = 1;

while(~done)
    [B C] = myFunction(list{ii});
    list = list{list{:}, B, C};

    for jj=1:numel(list)-2
       if(all(all(list{jj}==B)) || all(all(list{jj}==C)))
           done = 1;
       end
    end

    ii=ii+1;
end

end

更新:处理未知数量的输出的一种更通用的方法是修改myFunction ,以使其输出单个单元格向量内的所有矩阵。 这样,您可以通过以下方式连接列表:

[newMat] = myFunctions(list{ii}); % where newMat={B,C,...}
list = {list{:}, newMat{:}}; % or list=cat(2,list,newMat)

for jj=1:numel(list)-numel(newMat)
    for nn=1:numel(newMat) % checking for repetitions
        if(all(all(list{jj}==newMat{nn})))
            done=1;
        end
    end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM