MATLAB: Error using horzcat. CAT arguments dimensions are not consistent.

grpstatshorzcatStatistics and Machine Learning Toolbox

Dear all,
Using the next function, I get the error mentioned:
function [Y]=descriptiveStats( X )
M={};
N=[];
M={'mean','sem','numel','std','var','min','max'}.';
[mean,sem,numel,std,var,min,max]=grpstats(X,[],{'mean','sem','numel','std','var','min','max'});
N=[mean,sem,numel,std,var,min,max].';
Y=[M,N];
xlswrite('df.xlsx',Y)
end
The results displayed in the command window look like this:
>> dFStats = descriptiveStats(decodeFemale);
size(M)
7 1
size(N)
7 1
M
'mean'
'sem'
'numel'
'std'
'var'
'min'
'max'
N
1.7802
0.0935
186.0000
1.2749
1.6254
0
4.7137
Error using horzcat
CAT arguments dimensions are not consistent.
Error in descriptiveStats (line 20)
Y=[M,N];
However, if I use an additional argument gname that displays a character I don't get the aforementioned error:
function [Y]=descriptiveStats( X )
M={};
N=[];
M={'mean','sem','numel','gname','std','var','min','max'}.';
[mean,sem,numel,gname,std,var,min,max]=grpstats(X,[],{'mean','sem','numel','gname','std','var','min','max'});
N=[mean,sem,numel,gname,std,var,min,max].';
Y=[M,N];
xlswrite('df.xlsx',Y)
end
And this are the results printed in the command window:
>> dFStats = descriptiveStats(decodeFemale);
size(M)
8 1
size(N)
8 1
M
'mean'
'sem'
'numel'
'gname'
'std'
'var'
'min'
'max'
N
[1.7802]
[0.0935]
[ 186]
'1'
[1.2749]
[1.6254]
[ 0]
[4.7137]
It's not a big deal to have to use the gname argument in order to avoid the error, but I don't understand why it is happening.
Can somebody explain what's the cause and how to fix it?
Regards,
Diego

Best Answer

Easy. Without the gname argument, what is being returned is a simple 7 x 1 numeric array, which would occupy at most one cell entry rather than the 7 you would need in order to match the 7 x 1 cell array of strings you constructed in M. But when you use gname, it needs to return a string as part of the output and so cannot just return a numeric array, so it returns a cell array of the right size for you to match with M.
Solution:
[M, num2cell(N)]