Search code examples
arraysmatlabmatrixmismatch

Subscripted assignment dimension mismatch in Matlab with true index


I wrote this for loop to do something and I'm sure the size of this result array is equal to 30 but I don't know why this error is appear about the mismatch dimension !

for rno=1:30
    PersonNumber = outputtrainingdata(rno);
    RealOutput = finaloutputforeachrow(rno,PersonNumber);
    if round(RealOutput) == 1
        result(rno) = 'True';    % Error in this line 
        %result = 'True'
        TrueTrainingcounter = TrueTrainingcounter+1;
    else
        result(rno) = 'False';
        %result = 'False'
    end

 end

Solution

  • You are trying to assign the string 'True' (length = 4) to result(rno) (length = 1). Similarly you are trying to assign the string 'False' (length = 5) to result(rno) (length = 1). This is why you're getting a dimensions mismatch error.

    If you want result to actually hold these strings, then you'll want to use a cell array.

    result = cell(1, 30);
    

    And then assign to it using {}

    result{rno} = 'True';
    

    A much better approach is to use the logical values true and false rather than the strings 'True' and 'False'. Because length(true) == 1, we no longer will get a dimension mismatch.

    result(rno) = round(RealOutput) == 1;