Adding zeros to a column vector to match a larger column vector

조회 수: 8 (최근 30일)
S Suhaimi
S Suhaimi 2023년 12월 4일
답변: Steven Lord 2023년 12월 4일
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).

답변 (4개)

Les Beckham
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

Matt J
Matt J 2023년 12월 4일
편집: Matt J 2023년 12월 4일
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;

VBBV
VBBV 2023년 12월 4일
편집: VBBV 2023년 12월 4일
x = rand(100,1) % column vector
x = 100×1
0.8303 0.5510 0.2123 0.2285 0.4678 0.7940 0.1815 0.2479 0.1557 0.1806
y = rand(108,1) % another column vector of different size
y = 108×1
0.4289 0.9965 0.6628 0.3147 0.2230 0.9301 0.1332 0.8500 0.8675 0.4001
zeros(1,length(y)-length(x)) % row vector
ans = 1×8
0 0 0 0 0 0 0 0
new_x= [x',zeros(1,length(y)-length(x))]
new_x = 1×108
0.8303 0.5510 0.2123 0.2285 0.4678 0.7940 0.1815 0.2479 0.1557 0.1806 0.1557 0.2500 0.1559 0.4368 0.1118 0.3869 0.5771 0.1627 0.6922 0.1240 0.2174 0.2439 0.4261 0.1834 0.3268 0.1863 0.2051 0.1857 0.8732 0.1211
% ^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
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
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
Name Size Bytes Class Attributes x 100x1 800 double x2 108x1 864 double y 108x1 864 double y2 108x1 864 double
Since y was already the correct size, paddata didn't change it.
isequal(y, y2)
ans = logical
1
Let's look at the last dozen rows of x and x2.
tail(x, 12)
89 90 91 92 93 94 95 96 97 98 99 100
tail(x2, 12)
97 98 99 100 0 0 0 0 0 0 0 0
There are 8 copies of 0 at the end of x2 to make it the same size as y and y2.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by