Search code examples
arraysmatlabmatrixmatrix-indexing

MATLAB - Equivalent logical indexing leading to two different results


I'm writing a piece of code for submission through an online grader, as showcased below. B is some given array filled any/all integers 1 through K, and I want to extract the corresponding logical indices of matrix X and perform some operations on those elements, to be put into a return array:

for i = 1:K

   A = X(B == i, :);
   returnArr(i, :) = sum(A) / length(A);

end

This did not pass the grader at all, and so I looked to change my approach, instead indexing array X indirectly via first using the "find" function, as below:

for i = 1:K

    C = find(B == i);
    returnArr(i,:) = sum(X(C,:)) / length(C);

end

To my surprise, this code passed the grader without any issues. I know there are a plethora of variations between graders, and one might handle a particular function differently than another, but from a MATLAB functionality/coding perspective, what am I missing in terms of discrepancies between the two approaches? Thanks!


Solution

  • I think the problem is that:

    length(C) == sum(B == i)
    

    while

    length(A) == max([sum(B == i) , size(X , 2)])
    

    In other words, to obtain the same result of the second example with the first one, you should modify it like this:

    A = X(B == i , :);
    returnArr(i, :) = sum(A) / size(A,1);
    

    The function length returns the length of largest array dimension