MATLAB Matrix Extension with Zeros

I need the nxn matrix, where the first pxp of them contains those, and the rest are zeros. I can do this by going through the cells, so I am not asking to do this. I am looking for a “MATLAB path” for this, using built-in functions and avoiding loops, etc.

To be more clear;

let n=4 and p=2 ,

then the expected result:

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

There may be some more elegant solutions, so I will answer the shortest and most readable answer.

PS The title of the question looks somewhat irrelevant: I put this title because my initial approach would be to create a pxp matrix with units, and then expand it to nxn zeros.

+4
source share
4 answers

The answer is to create a matrix of zeros, and then set its part to 1 using indexing:

For instance:

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

If you insist on an extension, you can use:

 padarray( zeros(p,p)+1 , [np np], 0, 'post') 
+10
source

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 
+6
source

You can easily create a matrix by concatenating horizontally and vertically:

 n = 4; p = 2; MyMatrix = [ ones(p), zeros(p, np); zeros(np, n) ]; 
+2
source
 >> p = 2; n = 4; >> a = [ones(p, 1); zeros(n - p, 1)] a = 1 1 0 0 >> A = a * a' A = 1 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 
+1
source

Source: https://habr.com/ru/post/1415805/


All Articles