Search code examples
matlabloopsmatrix-indexing

For loop and matrix indexing in matlab ques


I have defined a matrix (initial_matrix) equal to 0 by using a for loop as:

I = 5;   % e.g number of nodes
for i =1:I
    initial_matrix = [0];    // an initial matrix will be generated for each node
end

Now, for each node i, I will consider all other nodes but not the node i itself and subtract each of them from 1 and take their product:

for node 1:

result = (1 - initial_matrix of node 2) * (1 - initial_matrix of node 3) * ...
    (1 - initial_matrix of node 4) * (1 - initial_matrix of node 5)

for node 2:

result = (1 - initial_matrix of node 1) * (1 - initial_matrix of node 3) * ...
    (1 - initial_matrix of node 4) * (1 - initial_matrix of node 5)

for node 3:

result = (1 - initial_matrix of node 1) * (1 - initial_matrix of node 2) * ...
    (1 - initial_matrix of node 4) * (1 - initial_matrix of node 5) 

and so..for the remaining 2 nodes!

Can any one tell me or give me hints on how this can be achieved? Thanks!


Solution

  • For each product (per node) you need to have all initial matrices in advance, so you should modify your initial loop to something along these lines:

    initial_matrix = cell(I, 1);
    for i = 1:I
        initial_matrix{i} = blah blah... %// Generated for each node
    end
    

    Then you can add another nested loop that does something like the following:

    result = cell(I, 1);
    for k = 1:I
    
        %// Compute product
        result{k} = 1;
        for n = setdiff(1:I, k)
            result{k} = result{k} * (1 - initial_matrix{n});
        end
    end