0
votes

I have a matrix M:

M=rand(n,m)

and an array K of length m^n

K=zeros(m^n,1)

The array K is filled in with the values obtained by summing up the values of the matrix M across n rows for all possible m^n vertical combination of cells. An auxiliary array Index of length m^n contains index references to the cell combinations so that the column indices of the Index array indicate the rows of matrix M and the values of the Index array – the columns of the matrix M. In the example below for 4x3 matrix, the second row {1,1,1,2} of the Index array corresponds to the combination of cells M(1,1), M(2,1),M(3,1) and M(4,2) etc:

Index =

     1     1     1     1
     1     1     1     2
     1     1     1     3
     1     1     2     1
…

This index referencing is then used to calculate the values (sum) of each cell combination which are stored in K:

for i=1:m^(n)
    for j=1:n
                K(i)= K(i)+M(j,Index(i,j))
    end
end

Until this point it works fine. What I need, however, is to introduce an “if” condition so that if any of the cell of matrix M is equal to zero, than the value of any combination containing this zero-value (cell(s)) will be also zero. I have tried to introduce it within the for-loop:

Assume

M(1,1)=0
M(3,1)=0

Then

for i=1:m^(n)
    for j=1:n
        if M(j,Index(i,j))~=0
                K(i)= K(i)+M(j,Index(i,j)) 
        else
            K(i)=0
        end
    end
end

This solution does not seem to work because it fails to identify the cell combinations associated with zero-value cells and I cannot figure out the way around it. Does anyone know how to solve this? Thank you!

1

1 Answers

1
votes

If I understand your explanation correctly...

Once your code has found a matrix element equal to zero it should break out of the inner for loop instead of continuing to sum. Try this:

for i=1:m^(n)
    for j=1:n
        if M(j,Index(i,j))~=0
                K(i)= K(i)+M(j,Index(i,j)) 
        else
            K(i)=0
            break
        end
    end
end

You should also be careful that for floating point numbers, such as the ones yielded by rand, they may not quite be equal to zero.