convert table to string in matlab

To convert a table to a string in Matlab, you can use the table2array and mat2str functions together. Here's an example:

main.m
% sample table
T = table({'a'; 'b'; 'c'}, [1; 2; 3], logical([1; 0; 1]), ...
    'VariableNames', {'Letter', 'Number', 'Flag'});

% convert table to cell array of strings
C = table2cell(T);
Cstr = cellfun(@mat2str, C, 'UniformOutput', false);

% join cell array of strings into one string
str = strjoin(Cstr, ', ');

disp(str);
328 chars
13 lines

This will output the following string:

main.m
'a', [1], [true], 'b', [2], [false], 'c', [3], [true]
54 chars
2 lines

Note that this method uses square brackets to represent the values in the table, even if they are not numeric. If you want to enclose non-numeric values in single quotes, you can modify the mat2str call to add the ' characters:

main.m
Cstr = cellfun(@(x) ['''', x, ''''], C, 'UniformOutput', false);
65 chars
2 lines

This will output a string like this:

main.m
'a', '1', 'true', 'b', '2', 'false', 'c', '3', 'true'
54 chars
2 lines

related categories

gistlibby LogSnag