简体   繁体   中英

"Index exceeds matrix dimensions" error

I run a code and "Index exceeds matrix dimensions" appears as an error but I don't understand why.

Here is the code:

function [ p ] = myIsort2(p)
%myIsort2 is based on myIsort but instead of sorting a row vector into 
%increasing order it sorts a structure array into decreasing order

global order

n=length(p);

for i=2:n

    x=p(1,i).exponent;
    y=p(1,i).coeff;
    j=i-1;

    while (j~=0) && order(x,p(1,j).exponent)==1

        %compares the order between 2 row vectors of the exponential field 
        %in order to sort them by making the smallest one come after the
        %largest one

        p(1,j+1).exponent=p(1,j).exponent;
        p(1,j+1).coeff=p(1,j).coeff;
        j=j-1;

    end

    p(1,j+1).exponent=x;
    p(1,j+1).coeff=y;

end

end

Thanks.

The problem could be accessing p , which is accessed with indices going from p(1,1) to p(1,n) with n = length(p) .

If you are getting an index exceeds matrix dimensions error, the conclusion is that p has less than n columns. Note that length is the size of the largest dimension of p . So if p has more rows than columns, this error will show up.

An example:

  • Suppose p is <10x5 double> .
  • n = length(p) returns n = 10 .
  • However, p(1,10) returns Error: index exceeds matrix dimensions because p has only 5 columns.

Instead of length , use size to get the sizes of all dimensions, or numel to get the total number of elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM