How to add zeros to the end of an array

조회 수: 467 (최근 30일)
Vishnu M S
Vishnu M S 2013년 1월 29일
답변: Steven Lord 2023년 11월 29일
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
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
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
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
Md Rezaul Karim
Md Rezaul Karim 2021년 1월 26일
Thank you Jan
Jan
Jan 2021년 1월 26일
@Black4Ghost: Filling with characters works by:
[YourData, rempmat('0', 1, wantedWidth - numel(YourData))]

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

Azzi Abdelmalek
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
Jan
Jan 2013년 1월 29일
B(end) overwrites the last element of B.
Azzi Abdelmalek
Azzi Abdelmalek 2013년 1월 29일
B(end+1:numel(A))=0

댓글을 달려면 로그인하십시오.


Mohammad Sohail Khan
Mohammad Sohail Khan 2017년 10월 3일
Thank You

Steven Lord
Steven Lord 2023년 11월 29일
If you're using release R2023b or later, you could use paddata or resize to do this.
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)
A2 = 1×10
1 5 3 8 9 4 7 6 5 2
B2 = paddata(B, n)
B2 = 1×10
5 2 3 9 7 4 5 0 0 0
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
A3 = 1×8
1 5 3 8 9 4 7 6
B3 = resize(B, 8) % add one 0 at the end
B3 = 1×8
5 2 3 9 7 4 5 0
There's also trimdata to always make it the desired length or shorter.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by