Search code examples
arraysmatlabmatrixconcatenation

Concatenating double array with string array in Matlab R2018a vs R2020b


I am trying to concatenate on the third dimension a 3x3x2 double array (AA) with a 3x3 string array (BB) using the function cat.

AA = zeros(3,3,2)
BB = ["blue" , "yellow" , "red" ; "car" , "bike" , "van" ; "apple" , "pear" , "orange"]

Z = cat(3,AA,BB)

While these three lines of code work in Matlab R2020b, in Matlab R2018a I get this error:

Error using cat. Dimensions of arrays being concatenated are not consistent.

Any workaround to make it work for Matlab R2018a (due to some restrictions, I cannot upgrade version at the moment)?


Solution

  • I initially thought it was the different types that would be problematic. But I learned that When concatenating a double array and a string array, the double array is converted to a string array.

    It seems that there is a bug in R2018a (and R2017a that I used here as well) that breaks this particular use case. This works perfectly well:

    AA = zeros(3,3,1);
    BB = ["blue", "yellow", "red"; "car", "bike", "van"; "apple", "pear", "orange"];
    Z = cat(3,AA,BB);
    

    To avoid this bug, we can write a cat function ourselves. This code is specific for concatenating along the 3rd dimension, and it doesn't bother testing the sizes of the arrays, assuming they're OK.

    sz = size(AA);
    n = size(AA,3);
    sz(3) = n + size(BB,3);
    % Here we assume size(BB,1)==sz(1) and size(BB,2)==sz(2)
    Z = strings(sz);
    Z(:,:,1:n) = AA;
    Z(:,:,n+1:end) = BB;
    

    I suggest you create a function with this code, and replace your calls cat(3,...) with calls to this function.