Search code examples
matlabiterationmatlab-table

How can I create a table to hold data from an iteration in MATLAB?


Let us suppose that we have two matrices as input, X and Y. I would like to regress each column of Y on each column of X and calculate several parameters, then create a table for the results. Here is my starting code:

function [Table]=create_table(Y,X)
    [n,p]=size(X); % size of both matrix is X
    for ii=1:p % iterate  over all variable 
        x=X(:,i);
        y=Y(:,ii);
        x = [ones(size(x)) x];% construct  X matrix 
        [b,~,~,~,~] = regress(y,x);

        %% let us suppose we would like to calculate two parameters
        unknown=b(1)*100-b(2);
        known=b(2)/b(1)+200
    end
end

What I want to get as a result is following table (let us suppose that p = 3):

enter image description here

I know there is a table command in MATLAB, but I don't know how to use it here?


Solution

  • Immediately before your for loop, you can initialize your table (filled with zeroes to start) like so:

    T = table((1:p).', zeros(p, 1), zeros(p, 1), ...
              'VariableNames', {'Iteration', 'Unknown', 'Known'});
    

    Then you can fill in rows of your table within your loop by replacing the calculations of unknown and known with this:

    T.Unknown(ii) = b(1)*100-b(2);
    T.Known(ii) = b(2)/b(1)+200;