how to horizontally concatenate columns of different types

Hello, In my workspace I have a variable Z with strings (5082 x 1 cell), and a variable Y with numbers (5082 x 4360 single).
I would like to concatenate these two variables horizontally in order to obtain a matrix or something that I can then export into Excel/text file, with 5082 rows and 4361 columns.
I also need the column with strings to be the first column of the matrix/array/etc.
I have tried with: matrix={[char(Z),num2str(Y)]}; but it doesn't do what I want. It gives me a 1 x 1 cell.
I have also tried: mixed_array = cat(1, Z, Y); and again it doesn't do what I want. It results in a 5083 x 1 cell, with the 5082 rows from the variable Z and the last row (5083th) with the entire Y variable (5082 x 4360 single).
If I do: mixed_array = cat(2, Z, Y); it gives me this Error: "Error using cat Dimensions of matrices being concatenated are not consistent."
Any suggestions about how to do it?
Many thanks!

Answers (1)

I think your best bet is for the final object to be a cell array, so try this:
Z = cell(5082,1);
Y = single(rand(5082,1));
% Put each numeric into a cell, then concatenate:
M = [Z,num2cell(Y)];
Also, I like this cellwrite function from the File Exchange for writing cell arrays to CSV files. (I am on a Mac, so the MATLAB tools are somewhat crippled.)

2 Comments

@the cyclist, Thanks for your answer! I tried to use your script: M = [Z,num2cell(Y)]; but my computer crashes for more than 3 hours, and after this time, still no output. Do you think that the problem is the memory of my computer? Or is normal that this formula requires a lot of time to produce an output? Many thanks.
The exact code in my example took 0.01 seconds to run on my computer.
I suggest running your code on a very small subset of your data, and see if it returns quickly. Then maybe you could profile your code to see what is so slow.

Sign in to comment.

Categories

Asked:

on 25 Sep 2015

Commented:

on 29 Sep 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!