Question

I am quite new to MATLAB. I would like to know how can I transfer the matrix A to matrix B as shown below?

A = 1 2
    3 4
    5 6

B=0 0 0 0
  1 1 2 1
  1 3 4 1
  1 5 6 1
  0 0 0 0

Essentially I would like to add a boundary to A.

Thank you!

Was it helpful?

Solution

padarray implementation -

%// pad ones on left-right and then pad zeros on top-bottom
B = padarray(padarray(A,[0 1],1),[1 0],0)

OTHER TIPS

If I understand your question correctly, you wish to insert a 1 element boundary surrounding the matrix. In that case, try something like this:

A = [1 2; 3 4; 5 6];
[rows,cols] = size(A);
B = zeros(rows+2, cols+2);
B(2:end-1,[1 end]) = 1;
B(2:end-1,2:end-1) = A;

However, you can also use padarray like what @Divakar has suggested. Much more elegant!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top