matlabfor-loopvariable-length

For loop continuing past set end point (matlab)


I have an array of matrices which are all different lengths. I want to compare the distance of each item in matrix 1 to the items in matrix 2 and so on. The for loops I've written below work well except when it reaches a matrix which is length 2. The loop continues to xx = 3 and then calls an error ("Index in position 1 exceeds array bounds. Index must not exceed 2.") because there is no current_mat(3,:). Why is it doing this only for matrices of length 2? I'm relatively new to matlab, so apologies if this is a simple question. Here are some toy data that give the same error I am seeing with a larger dataset.

matrix_1 = ones(16,3)
matrix_2 = ones(14,3)
matrix_3 = ones(2,3)
matrix_4 = ones(10,3)
my_array = {matrix_1; matrix_2; matrix_3; matrix_4}

for ii = 1:length(my_array)-1;
    current_mat = my_array{ii};
    compare_mat = my_array{ii+1};
    for xx = 1:length(current_mat);
        xx_info = current_mat(xx,:);
    end
end

Solution

  • The issue is that when given a matrix input length returns the longest dimension of the matrix, not the number of rows. In the case of your matrix_3 this is 3 although it appears that you expect 2. So xx goes from 1 to 3 and in line 11 you attempt to access a row that doesn't exist when xx=3. Better would be to explicitly loop across the m dimension. You can do this with size which returns the number of rows and columns in the matrix:

    matrix_1 = ones(16,3)
    matrix_2 = ones(14,3)
    matrix_3 = ones(2,3)
    matrix_4 = ones(10,3)
    my_array = {matrix_1; matrix_2; matrix_3; matrix_4}
    
    for ii = 1:length(my_array)-1;
        current_mat = my_array{ii};
        compare_mat = my_array{ii+1};
        [m,n] = size(current_mat); % <-- use size here, not length
        for xx = 1:m;
            xx_info = current_mat(xx,:);
        end
    end 
    

    or, if you wish to look at the columns:

    matrix_1 = ones(16,3)
    matrix_2 = ones(14,3)
    matrix_3 = ones(2,3)
    matrix_4 = ones(10,3)
    my_array = {matrix_1; matrix_2; matrix_3; matrix_4}
    
    for ii = 1:length(my_array)-1;
        current_mat = my_array{ii};
        compare_mat = my_array{ii+1};
        [m,n] = size(current_mat); % <-- use size here, not length
        for xx = 1:n;
            xx_info = current_mat(:,xx);
        end
    end