error using writetable unsupported type 'char'. use writematrix instead in matlab

To avoid the error "Unsupported type 'char'. Use writematrix instead" when trying to write data to a file using writetable in MATLAB, you can use the function writematrix instead.

The writetable function is used to write tables to text files, while the writematrix function is used to write numeric arrays to text files. If you want to write a character array to a file, you can use the fprintf function.

Here's an example of how to use the writematrix function to write data to a text file:

main.m
A = magic(3);
writematrix(A, 'mydata.txt', 'Delimiter', 'tab');
64 chars
3 lines

This will write the matrix A to the file mydata.txt, using tabs as the delimiter between columns. You can change the delimiter to a comma or space as needed by changing the second input argument of the function.

To handle the error and avoid it being thrown, you can use a try-catch block as shown below:

main.m
try
    writetable(T,'mytable.txt')
catch ME
    if strcmp(ME.identifier,'MATLAB:table:write:UnsupportedVariableType')
        writematrix(T{:,:},'mytable.txt')
    else
        rethrow(ME)
    end
end
202 chars
10 lines

In this case, we are trying to write a table T to file mytable.txt. If the writetable function throws an error due to an unsupported variable type, we catch the error and if it matches the MATLAB:table:write:UnsupportedVariableType identifier, we use writematrix to write the data to the file instead. Otherwise, we rethrow the error as it is.

gistlibby LogSnag