How to Pad an Array with extra zeros

25 ビュー (過去 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 Center および File ExchangeOperators and Elementary Operations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by