Search code examples
matlabloopsrecursionoverwriteorganization

matlab organize results so they do not overwrite in recurent loop


I would like to organize these results and trace them somehow. I don't know how to keep going until a size 2 matrix is reached. Also there may be a better way of doing what I want, it would make me very happy.

Edit: I would like to be able to see the results from more levels of recursing. The problem is I don't know how to send results from level 10 to the first level so that it can be used for the entire program. Also I am not sure I can trace them to know all the values for all the i's for each result, meaning which lines/columns were deleted.

clc
close all
clear all
fclose('all');
d2=[0   -1.165  -3.5493 -2.3828 -1.1464
1.165   0       -2.3843 -1.2178 0.0186
3.5493  2.3843  0       1.1665  2.4029
2.3828  1.2178  -1.1665 0       1.2364
1.1464  -0.0186 -2.4029 -1.2364 0];

[a,f] = smaller(d2, 0);

function [e,next] = smaller(d, level)
    [Rows,~] = size(d);
    level = level + 1;
    for i = 1 : Rows
        d_s = d;
        d_s(i,:) = [];
        d_s(:,i) = [];
        e(i,1) = s2a(eig(d_s));
        if nnz(d_s) > 11
            [next(:,i)] = smaller(d_s, level);
            end
        end
    end
    
function f = s2a(u)
    Rows = size(u);
    f = 0;
    for i = 1 : Rows
        f = f + u(i)*u(i);
        end
    end

The results for all smaller 5x5 matrices are:a

-31.6632098200000
-56.5056698200000
-22.7225231200000
-53.4562986200000
-56.3222738200000

for all smaller 4x4:f

-17.3266712400000   -17.3266712400000   -6.02413552000000   -22.9183217200000   -17.0572911600000
-6.02413552000000   -17.0413075200000   -17.0413075200000   -39.3713837200000   -39.2719771600000
-22.9183217200000   -39.3713837200000   -5.34360784000000   -5.34360784000000   -17.0359953600000
-17.0572911600000   -39.2719771600000   -17.0359953600000   -39.2792839600000   -39.2792839600000

I would like all results for all smaller matrices, and a way to organize them.


Solution

  • I came upon this other much faster way of doing it:

    S=dec2bin(1:2^size(d1,1)-1)=='1';
    b=cell(size(S,1),1);
    for ix=1:size(S,1)
        b{ix}=d1(find(S(ix,:)),find(S(ix,:)));
        if isempty(b{ix})<1
            e(ix,1)=s2a(eig(b{ix}));
            end
        end