Search code examples
matlabfor-loopdimensionmismatch

Dimension Mismatch MatLab; cant figure out why it is mismatching


I think it may be a syntax issue, here is the code.

  load ([ 'C:\Users\Abid\Desktop\Inquiry Runs\dtS' ])
 dtS((dtS==0))=nan;
 for j=2:9;
maxS=max(dtS(j,:));
minS=min(dtS(j,:));

maxval(j,:)=dtS((dtS>(maxS-.1*maxS)));
minval(j,:)=dtS((dtS<(minS+.1*minS)));

avmax(j)=mean(maxval(j,:));
avmin(j)=mean(minval(j,:));

avs(j,:)=[avmax(j) avmin(j)]
 end

So I know the the row matrices are different sizes every loop. For example maxval(j,:) will change depending one row it is looking through for certain values.

I did this manually and I see that on the first loop the matrices are size (1,1), however, if I set the loop to run for only j=2, the row length is 13.

Usually if a matrix is changing size on the loop, I only get a warning, but this time I think it is due to a reason I don't understand.


Solution

  • You are right that the problem is with maxval(j, :) being a different size. length(maxval(j, :)) is not length(dtS((dtS>(maxS-.1*maxS)))); this causes a problem since maxval has to be 'rectangular', but if it were extended by this line of code, some of its values would not be defined. Consider:

    x = [1, 2; 3, 4];
    x(3, :) = [5, 6, 7];
    

    If this code were legal, the result would be:

    x: [1, 2, ?;
        3, 4, ?;
        5, 6, 7]
    

    and because of those undefined values, matlab will not let you do this. You could use a cell array instead:

    maxval = cell(9, 1);
    avmax = zeros(9, 1);
    avs = zeros(9, 2);
    for j=2:9;
      maxS=max(dtS(j,:));
      minS=min(dtS(j,:));
    
      maxval{j} = dtS((dtS>(maxS-.1*maxS)));
      minval{j} = dtS((dtS<(minS+.1*minS)));
    
      avmax(j)=mean(maxval{j});
      avmin(j)=mean(minval{j});
    
      avs(j,:)=[avmax(j) avmin(j)]
    end