How to Pad an Array with extra zeros

조회 수: 23 (최근 30일)
Shaquille Powell
Shaquille Powell 2017년 10월 23일
편집: Stephen23 2017년 10월 23일
Say I have an array, and I use to reshape function to divide it into equal sections. In the case that it cannot be divided into equal sections, how do I add zeros at the end to compensate? Say A=[1 8 1 9 1 4 1 5 0 4], and I want to divide it into sections of 4. 4 is not a set value.
  댓글 수: 1
Shaquille Powell
Shaquille Powell 2017년 10월 23일
I'm new to this so I keep asking confusing questions. I want the end up with B=[1 8 1 8,1 4 1 5, 0 4 0 0]

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

채택된 답변

Stephen23
Stephen23 2017년 10월 23일
편집: Stephen23 2017년 10월 23일
Here are some simple methods that automatically adjusts to the length of the vector:
Method One: pad to end of vector:
>> A = [1,8,1,9,1,4,1,5,0,4];
>> N = 4;
>> B = A;
>> B(end+1:N*ceil(numel(B)/N)) = 0
B =
1 8 1 9 1 4 1 5 0 4 0 0
Method Two: preallocate a vector of the right size:
>> A = [1,8,1,9,1,4,1,5,0,4];
>> N = 4;
>> B = zeros(1,N*ceil(numel(A)/N));
>> B(1:numel(A)) = A
B =
1 8 1 9 1 4 1 5 0 4 0 0

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2017년 10월 23일
편집: Andrei Bobrov 2017년 10월 23일
A=[1 8 1 9 1 4 1 5 0 4];
n = 4;
B = reshape([A(:);zeros(mod(-numel(A),n),1)],n,[])';

KSSV
KSSV 2017년 10월 23일
편집: KSSV 2017년 10월 23일
doc padarray
B = [A zeros(1,2)]

카테고리

Help CenterFile Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by