How can I expand a matrix with zeroes 开发者_StackOverflow中文版around the edge and then crop it back to the same size, after some manipulations?
You can do this:
octave:1> x = ones(3, 4)
x =
1 1 1 1
1 1 1 1
1 1 1 1
octave:2> y = zeros(rows(x)+2, columns(x)+2);
octave:3> y(2:rows(x)+1, 2:columns(x)+1) = x
y =
0 0 0 0 0 0
0 1 1 1 1 0
0 1 1 1 1 0
0 1 1 1 1 0
0 0 0 0 0 0
octave:4> y = y.*2 (manipulation)
y =
0 0 0 0 0 0
0 2 2 2 2 0
0 2 2 2 2 0
0 2 2 2 2 0
0 0 0 0 0 0
octave:5> x = y(2:rows(x)+1, 2:columns(x)+1)
x =
2 2 2 2
2 2 2 2
2 2 2 2
To pad an array, you can use PADARRAY, if you have the image processing toolbox.
Otherwise, you can pad and shrink the following way:
smallArray = rand(10); %# make up some random data
border = [2 3]; %# add 2 rows, 3 cols on either side
smallSize = size(smallArray);
%# create big array and fill in small one
bigArray = zeros(smallSize + 2*border);
bigArray(border(1)+1:end-border(1),border(2)+1:end-border(2)) = smallArray;
%# perform calculation here
%# crop the array
newSmallArray = bigArray(border(1)+1:end-border(1),border(2)+1:end-border(2));
精彩评论