Merge two columns into one

Hello everyone, A quick question: I want to merge two columns into one. What I've tried -
x = [1;2;3]; % (3x1 size)
y = [5;6;7]; % (3x1 size)
XY = [x y]; % (3x2 size)
[ 1 5
2 6
3 8]
versus what i ultimately want
xy = [15;26;38]; % (3x1 size)
Any thoughts? I was looking into reshape as well but that would also give me a 3x2 variable. Thanks,

3 comentarios

Adam
Adam el 8 de Sept. de 2017
Editada: Adam el 8 de Sept. de 2017
Where does [15;26;38] come from when you start with [1;2;3] and [5;6;7]? That's not what I would call 'merging'.
Reshape gives you whatever shape you tell it to provided there are the correct number of elements.
I assume you mean you want to concatenate the two columns of numbers, which would require you to convert them to chars I would think...e.g.
str2num( [num2str( x ) num2str( y )] )
I imagine there is a neater way though. str2num is not a pleasant function to have to use!
OCDER
OCDER el 8 de Sept. de 2017
Editada: OCDER el 8 de Sept. de 2017
Is there a mathematical workaround? For instance:
xy = 10*x+y
xy =
15
26
37
If not, yup, it gets pretty messy as Adam said.
[ numbers -> strings -> combined string -> number ] is the workaround.
str2double(sprintf('%d%d', x, y))
sprintf is generally faster if combining multiple numbers to a single string.
str2double is faster than str2num for some reason.
Adam
Adam el 11 de Sept. de 2017
str2double doesn't use eval, which is good, but it wouldn't work in my solution. I can't remember off-hand what it resulted in, but it wasn't the required answer!

Iniciar sesión para comentar.

Respuestas (1)

Stephen23
Stephen23 el 11 de Sept. de 2017
Editada: Stephen23 el 11 de Sept. de 2017

3 votos

Ugly eval is not required, a simple use of sprint and sscanf is more efficient:
>> x = [1;2;3];
>> y = [5;6;8];
>> sscanf(sprintf('%d%d,',[x.';y.']),'%d,')
ans =
15
26
38
This is more than four times faster than the accepted answer (1e4 iterations):
Elapsed time is 3.26133 seconds. % accepted answer
Elapsed time is 0.716072 seconds. % my answer

2 comentarios

Natasha Sekhon
Natasha Sekhon el 11 de Sept. de 2017
Ok, great! Yes, i 'm new to using Matlab and appreciate the talk about using eval.
Stephen23
Stephen23 el 11 de Sept. de 2017
@Natasha Sekhon: you might like to read this thread, it has a few points that are worth keeping in mind when learning MATLAB:

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 8 de Sept. de 2017

Comentada:

el 11 de Sept. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by