How to add zeros to the end of an array
228 ビュー (過去 30 日間)
古いコメントを表示
I have two arrays like A=[ 1 5 3 8 9 4 7 6 5 2 ] & B=[ 5 2 3 9 7 4 5 ]
In 'A', I have 10 elements(say m) and in 'B', I have 7(say n) elements. I need to add 10-7=3 (m-n) zeros to the end of B.
Please help.
2 件のコメント
Becky CNS
2018 年 3 月 15 日
移動済み: Dyuman Joshi
2023 年 11 月 29 日
I am trying to do this but with A and B as matrices. The error message I get is 'Dimensions of matrices being concatenated are not consistent'. All I want to do is add zeros to another vector the length of A-B. How would I change the above code?
Jan
2018 年 3 月 15 日
移動済み: Dyuman Joshi
2023 年 11 月 29 日
If you post your code, we could fix it directly. This would be more convenient and useful than to create an artificial example.
A = rand(3,4);
B = rand(2,2);
B(size(A,1), size(A,2)) = 0;
A - B
採用された回答
Jan
2013 年 1 月 29 日
編集済み: Jan
2013 年 1 月 29 日
Matlab fills missing elements with 0 automatically:
A = [1 5 3 8 9 4 7 6 5 2];
B = [5 2 3 9 7 4 5];
B(numel(A)) = 0;
Less efficient, but working also:
B = [B, zeros(1, length(A) - length(B))];
12 件のコメント
Jan
2021 年 1 月 26 日
@Black4Ghost: Filling with characters works by:
[YourData, rempmat('0', 1, wantedWidth - numel(YourData))]
その他の回答 (3 件)
Azzi Abdelmalek
2013 年 1 月 29 日
編集済み: Azzi Abdelmalek
2013 年 1 月 29 日
A=[ 1 5 3 8 9 4 7 6 5 2 ];
B=[ 5 2 3 9 7 4 5 ];
B(end:numel(A))=0
2 件のコメント
Steven Lord
2023 年 11 月 29 日
A=[ 1 5 3 8 9 4 7 6 5 2 ];
B=[ 5 2 3 9 7 4 5 ];
n = max(length(A), length(B)); % using length is okay since A and B are both vectors
If we always want to make the vector longer or keep it the same size, use paddata.
A2 = paddata(A, n)
B2 = paddata(B, n)
If you want to append to the vector or remove elements depending on whether it's shorter or longer than your desired size, use resize.
A3 = resize(A, 8) % drop last 2 elements
B3 = resize(B, 8) % add one 0 at the end
There's also trimdata to always make it the desired length or shorter.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!