Search code examples
matlabcharstoredimension

Subscripted assignment dimension mismatch error for `char` variable


I get an error of ??? Subscripted assignment dimension mismatch. when days value reaches 13 because probably legend_vec column size for 7th row reaches 13.

days = [1     2     3     4     5     6    13];
for i=1:nTime
    legend_vec(i,:)=(['After ',num2str(days(i)),' days']);
end

How can I avoid the error and store all days as I am storing in legend_vec? Thanks.


Solution

  • When you attempt to store the composite string into an array, it will store it as a list of the Ascii or Unicode character numbers. So if I try to insert the string 'Hello world' as the first row of an array, then that first row will actually be:

    >>> my_strs = []; 
    >>> my_strs(1,:) = "Hello world"
    my_strs =
    
    72   101   108   108   111    32   119   111   114   108   100
    

    Notice that this implicitly makes my_strs into a 1-by-11 array. If I try to add a string as a second row, but it doesn't evaluate to have 11 character codes of length, it will give an error:

    >>> my_strs(2,:) = "Hi there"
    error: A(I,J,...) = X: dimensions mismatch
    

    So you either need to add whitespaces to pad the length of all your days when they become strings (so all your strings have uniform length), or do something more convenient, like store all the strings into a cell array where they can have different lengths.

    To do it with a cell array, you would do something like this:

    >>> my_strs = {};
    >>> my_strs{1} = "Hello world"
    my_strs =
    
    {
      [1,1] = Hello world
    }
    
    >>> my_strs{2} = "Hi there"
    my_strs =
    
    {
      [1,1] = Hello world
      [1,2] = Hi there
    }
    
    >>> my_strs{1,1}
    ans = Hello world
    >>> my_strs{1,2}
    ans = Hi there
    

    It should be straightforward to map that onto the index conventions you're using in the loop you display in the question above.

    Full disclosure: I am testing the above code using Octave, because I personally prefer to boycott Matlab. You can ask in meta or something if you care about why that is, but for the purposes of this question, I don't think that testing in Octave makes any difference in what the right answer is.