user161816
user161816

Reputation: 123

Record the number of iterations in a for loop into a Matlab table

I am trying to keep a track of all the calculations happening under 3 for loops. The data is too big therefore it is hard to keep the track of the data. Hence, I would like to construct a table which will record the number of iterations taking place inside every for loop.

The code:

for i = 1:4
    % Calculations
    i
    for j = 1:3
        % Calculations
        j
        for k = 1:3
            % Calculations
            k
        end
    end
end

So, the tabular output which I am expecting is like this,

enter image description here

Can anybody please help me in achieving this task.

Upvotes: 0

Views: 88

Answers (2)

Suever
Suever

Reputation: 65430

You could use ndgrid to create all permutations of your i, j, and k values and then have a single for loop that loops through all permutations.

[ii, jj, kk] = ndgrid(1:4, 1:3, 1:3);

% Pre-allocate your results matrix
results = zeros(size(ii));

for n = 1:numel(ii)
    % Do calculation with ii(n), jj(n), kk(n)
    results(n) = ii(n) + jj(n) + kk(n);
end

Now if you want to know what the ii, jj, or kk values were for a particular entry in results, you can just index into all variables the same way.

result_of_interest = results(100);
i_of_interest = ii(100);
j_of_interest = jj(100);
k_of_interest = kk(100);

If you really need tabular output, you can transform ii, jj, and kk into your table.

data = cat(2, ii(:), jj(:), kk(:))';

Upvotes: 2

Guillaume Jacquenot
Guillaume Jacquenot

Reputation: 11717

You can try the following code, where you declare the dimension of each loop at the beginning, and allocate a track matrix.

ni=3
nj=4
nk=5

track = zeros(3,ni*nj*nk);

offset = 1
for i = 1:ni
    % Calculations
    i
    for j = 1:nj
        % Calculations
        j
        for k = 1:nk
            % Calculations
            k
            track(1,offset) = i;
            track(2,offset) = j;
            track(3,offset) = k;
            offset = offset + 1;
        end
    end
end

Upvotes: 0

Related Questions