Hello, how can i zero pad inside a matrix ? For example :
if true
% code
end
A = [ 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16]
And i want
A = [ 1 2 3 4
5 6 7 8
0 0 0 0
0 0 0 0
......
0 0 0 0
0 0 0 0
9 10 11 12
13 14 15 16]
I know padarray can zero pad but only outside not in the inside.. Thank you.

 채택된 답변

Star Strider
Star Strider 2016년 5월 17일

0 개 추천

Create a second matrix of zeros, then assign the appropriate rows of your first matrix to the rows you want in the second matrix:
A = [ 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16];
Desired_Rows = 10; % Pick A Number
B = zeros(Desired_Rows, size(A,2));
B([1:2 end-1:end],:) = A
B =
1 2 3 4
5 6 7 8
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
9 10 11 12
13 14 15 16

댓글 수: 6

Thank you for your answer. I don't really understand that line : B([1:2 end-1:end],:) = A
For example, if my initial matrix has 20 rows and I want
if true
% code
end
myFirst10Rows
40RowsOfZeros
myLast10Rows
Thank you
My pleasure.
The assignment:
B([1:2 end-1:end],:) = A
creates a vector of row indices ‘[1:2 end-1:end]’ indicating the first two rows (the ‘1:2’) and the last two rows (the ‘end-1:end’), using the colon operator to create the continuity.
For your (20xN) matrix, my slightly revised code becomes:
B = zeros(size(A,1)+40, size(A,2));
B([1:10 end-9:end],:) = A
This creates a (60xN) matrix of zeros (in your example), then fills the first 10 rows of it with the first 10 rows of ‘A’ and the last 10 rows of it with the last 10 rows of ‘A’. Note that ‘end-9’ is the tenth row from the end.
Experiment with the indexing to see how it works.
So
So 2016년 5월 17일
I understand now, and it works perfectly with my code. Thank you very much.
Star Strider
Star Strider 2016년 5월 17일
My pleasure.
If my Answer solved your problem, please Accept it.
Guillaume
Guillaume 2016년 5월 17일
In my opinion, it'd be simpler to split the original matrix and insert a zero matrix in between: B = [A(1:10, :); zeros(40, size(A, 2); A(11:20, :)]
Star Strider
Star Strider 2016년 5월 17일
I thought about that, but considered that this could be a ‘proxy problem’ and the rows could end up being inserted anywhere in the target matrix, not just at the ends. The approach I took allows for that more easily.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

질문:

So
2016년 5월 17일

댓글:

2016년 5월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by