Adding zeros to a column vector to match a larger column vector
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I have x where the dimension is (100x1) and y (108x1)
I use:
new_x= [x,zeros(1,length(y)-length(x))];
but I got an error saying (Error using horzcat. Dimensions of arrays being concatenated are not consistent).
0 comentarios
Respuestas (4)
Les Beckham
el 4 de Dic. de 2023
Editada: Les Beckham
el 4 de Dic. de 2023
new_x= [x; zeros(length(y)-length(x), 1)];
% ^ ^ switch the arguments to zeros
% use a semicolon instead of a comma
0 comentarios
VBBV
el 4 de Dic. de 2023
Editada: VBBV
el 4 de Dic. de 2023
x = rand(100,1) % column vector
y = rand(108,1) % another column vector of different size
zeros(1,length(y)-length(x)) % row vector
new_x= [x',zeros(1,length(y)-length(x))]
% ^transpose the x vector
Transpose the x vector since it is column vector whereas zeros(1,length(y)-length(x)) is the row vector. Both of them being concatenated using [ ] operator
1 comentario
VBBV
el 4 de Dic. de 2023
Alternately, you could transpose the row vector zeros(1,length(y)-length(x)) keeping the x vector same (without transpose)
Steven Lord
el 4 de Dic. de 2023
If you're using release R2023b or later, you could use the paddata function. Let's create some sample data:
% I have x where the dimension is (100x1) and y (108x1)
x = (1:100).';
y = (101:208).';
What sizes are the two vectors?
szX = size(x);
szY = size(y);
What is the size of the larger? I used my knowledge that they had the same number of dimensions here.
M = max(szX, szY);
Now pad and look at the sizes of the results.
x2 = paddata(x, M);
y2 = paddata(y, M);
whos x x2 y y2
Since y was already the correct size, paddata didn't change it.
isequal(y, y2)
Let's look at the last dozen rows of x and x2.
tail(x, 12)
tail(x2, 12)
There are 8 copies of 0 at the end of x2 to make it the same size as y and y2.
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!