Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB Expanding A Matrix with Zeros

I need a matrix of nxn, where the first pxp of it contains ones and rest are zeros. I can do it with traversing the cells, so I'm not asking a way to do it. I'm looking for "the MATLAB way" to do it, using built-in functions and avoiding loops etc.

To be more clear;

let n=4 and p=2,

then the expected result is:

1 1 0 0
1 1 0 0
0 0 0 0
0 0 0 0

There are possibly more than one elegant solution to do it, so I will accept the answer with the shortest and most readable one.

P.S. The question title looks a bit irrelevant: I put that title because my initial approach would be creating a pxp matrix with ones, then expanding it to nxn with zeros.

like image 413
Seçkin Savaşçı Avatar asked Jun 03 '12 11:06

Seçkin Savaşçı


2 Answers

The answer is creating a matrix of zeroes, and then setting part of it to 1 using indexing:

For example:

n = 4;
p = 2;
x = zeros(n,n);
x(1:p,1:p) = 1;

If you insist on expanding, you can use:

padarray( zeros(p,p)+1 , [n-p n-p], 0, 'post')
like image 150
Andrey Rubshtein Avatar answered Nov 02 '22 10:11

Andrey Rubshtein


Another way to expand the matrix with zeros:

>> p = 2; n = 4;
>> M = ones(p,p)
M =
     1     1
     1     1
>> M(n,n) = 0
M =
     1     1     0     0
     1     1     0     0
     0     0     0     0
     0     0     0     0
like image 27
Amro Avatar answered Nov 02 '22 11:11

Amro