MATLAB: How to create a matrix, table or a cell where in odd columns variables from matrix A and in even columns variabls from matrix B will be stored

cell arraysmatricestables

For instance, I have two matrices A = ones(5,24) and B = zeros(5,24), I need to create a matrix 'C', where the first column of 'C' will consist of elements of A(:,1), the second column of 'C' will consist of B(:,1), the third column of 'C' will consist of elements of A(:,2), the fourth column of 'C' will consist of B(:,2) and so on.
Also, I'd like to know how the same can be applied to cell arrays and how the table of the same format could be constructed from matrices? For loops are ok.
Many thanks.

Best Answer

This should work for numeric, cell and table, although Adam's is likely more efficient for numeric:
>> x1 = array2table(rand(3))
x1 =
3×3 table
Var1 Var2 Var3
_______ ________ _______
0.77917 0.56882 0.33712
0.93401 0.46939 0.16218
0.12991 0.011902 0.79428
>> x2 = array2table(randn(3),'VariableNames',{'Var4' 'Var5' 'Var6'})
x2 =
3×3 table
Var4 Var5 Var6
________ ________ ________
-0.88803 0.30352 0.73936
0.10009 -0.60033 1.7119
-0.54453 0.48997 -0.19412
>> x = [x1 x2]
x =
3×6 table
Var1 Var2 Var3 Var4 Var5 Var6
_______ ________ _______ ________ ________ ________
0.77917 0.56882 0.33712 -0.88803 0.30352 0.73936
0.93401 0.46939 0.16218 0.10009 -0.60033 1.7119
0.12991 0.011902 0.79428 -0.54453 0.48997 -0.19412
>> x = x(:,[(1:3)+[0;3]]) % requires 16b or later, otherwise use bsxfun
x =
3×6 table
Var1 Var4 Var2 Var5 Var3 Var6
_______ ________ ________ ________ _______ ________
0.77917 -0.88803 0.56882 0.30352 0.33712 0.73936
0.93401 0.10009 0.46939 -0.60033 0.16218 1.7119
0.12991 -0.54453 0.011902 0.48997 0.79428 -0.19412