How to create matrix with other matrixes by joining them?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Csanad Levente Balogh
el 11 de En. de 2021
Hi!
I'm trying to construct a matrix from the elements of several vectors, by joining them, For example:
a = [1 2 3];
b = [4 5 6];
c = [7 8 9];
d = [10 11 12];
And it should result in:
res =
1 4 2 5 3 6
7 10 8 11 9 12
Which is:
res =
a(1) b(1) a(2) b(2) a(3) b(3)
c(1) d(1) c(2) d(2) c(3) d(3)
I would need a method that can do this for any number of vectors with the same length.
Using a for loop and clever indexing would propably be one way, but I'm looking for a solution without using loops.
0 comentarios
Respuesta aceptada
Stephen23
el 11 de En. de 2021
a = [1 2 3];
b = [4 5 6];
c = [7 8 9];
d = [10 11 12];
res = reshape([a;c;b;d],2,[])
4 comentarios
Stephen23
el 11 de En. de 2021
Editada: Stephen23
el 11 de En. de 2021
"There is no rule for the number of input veectors"
The product of the arrangement vector exactly specifies how many vectors you would have to have.
In the general case rather than having lots of vectors stored as separate variables (which would be very bad data design) it would be much better to store them in one numeric matrix or one cell array. An example with a cell array:
C = num2cell(reshape(1:12*3,3,12).',2); % {[1,2,3],[4,5,6],...,[34,35,36]}
A = [3,4]; % arrangement
D = reshape(C,A(2),A(1)).';
M = reshape(vertcat(D{:}),A(1),[])
If the data were stored in one numeric matrix then you could just use permute and reshape.
Más respuestas (1)
Mathieu NOE
el 11 de En. de 2021
hello
here you are
no loops
res = zeros(2,2*size(a,2));
res(1,1:2:2*size(a,2)) = a;
res(1,2:2:2*size(a,2)) = b;
res(2,1:2:2*size(a,2)) = c;
res(2,2:2:2*size(a,2)) = d;
0 comentarios
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!