% The functions defined in this file, together with the data file 'chladni-basis.mat'
% allow you to look at your solutions to the Chladni plate problem.
%
% It works quite simply by dotting your coefficient vectors into the set of basis
% functions, defined on a 500x500 grid, then showing the result with pyplot.
%
% show_waves(x,basis_set) shows the actual wave-functions
% show_nodes(x,basis_set) shows the wavefunction zeros, where the sand gathers
% show_all_wavefunction_nodes(T,lambdas,basis_set) shows the zeros of all the eigenfunctions defined by the columns of T

load("chladni_basis.mat");

function fun = vector_to_function(x,basis_set)
    C   = reshape(basis_set,15,[]);     % flatten 500x500-vectors
                                        % to make 15x2500000 matrix
    fun = reshape(x' * C, [500,500]);   % Dot-product, reshape back
                                        % to 500x500
end

function show_waves(x,basis_set)
    fun = vector_to_function(x,basis_set);
    imagesc(fun);
end

function show_nodes(x,basis_set)
    fun   = vector_to_function(x,basis_set);
    nodes = exp(-50*(fun.*fun));
    imagesc(nodes);
end


function show_all_wavefunction_nodes(T,lams,basis_set)
    [lams,sorted_index]  = sort(lams);
    T = T(:,sorted_index);
    N = 15;
    m = 5;
    n = 3;

    img = zeros(5*520,3*520);
    for k=1:N
        fun = vector_to_function(T(:,k),basis_set);
        i = idivide(int32(k-1),n);
        j = mod(k-1,n);
        img((1+i*520):(i*520+500),(1+j*520):(j*520+500)) = fun(:,:);
    end

    imshow( exp(-50*img.*img));
end
