Adding zeros to a column vector to match a larger column vector
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(4 个)
Les Beckham
2023-12-4
编辑:Les Beckham
2023-12-4
new_x= [x; zeros(length(y)-length(x), 1)];
% ^ ^ switch the arguments to zeros
% use a semicolon instead of a comma
0 个评论
VBBV
2023-12-4
编辑:VBBV
2023-12-4
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 个评论
VBBV
2023-12-4
Alternately, you could transpose the row vector zeros(1,length(y)-length(x)) keeping the x vector same (without transpose)
Steven Lord
2023-12-4
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!