how to horizontally concatenate columns of different types
Show older comments
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)
the cyclist
on 25 Sep 2015
Edited: the cyclist
on 25 Sep 2015
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
dederi
on 29 Sep 2015
the cyclist
on 29 Sep 2015
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.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!