5

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.

4

4 に答える 4

10

答えは、ゼロの行列を作成し、1インデックスを使用してその一部を設定することです。

例えば:

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

拡張を主張する場合は、次を使用できます。

padarray( zeros(p,p)+1 , [n-p n-p], 0, 'post')
于 2012-06-03T11:03:57.953 に答える
7

行列をゼロで展開する別の方法:

>> 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
于 2012-06-03T11:40:04.933 に答える
2

水平方向と垂直方向に連結することで、行列を簡単に作成できます。

n = 4;
p = 2;
MyMatrix = [ ones(p), zeros(p, n-p); zeros(n-p, n) ];
于 2012-06-03T11:38:22.437 に答える
1
>> 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
于 2012-06-03T13:40:10.530 に答える