Adding zeros to a column vector to match a larger column vector
Show older comments
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).
Answers (4)
Les Beckham
on 4 Dec 2023
Edited: Les Beckham
on 4 Dec 2023
new_x= [x; zeros(length(y)-length(x), 1)];
% ^ ^ switch the arguments to zeros
% use a semicolon instead of a comma
This gracefully handles the case when length(x)=length(y), and requires no consideration of whether x,y are row or column vectors.
x(end+1:numel(y))=0;
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 Comment
VBBV
on 4 Dec 2023
Alternately, you could transpose the row vector zeros(1,length(y)-length(x)) keeping the x vector same (without transpose)
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.
Categories
Find more on Matrices and Arrays 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!