Adding zeros to a column vector to match a larger column vector
7 ビュー (過去 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!