Eiffelcheung
Eiffelcheung

Reputation: 13

How to creat a matrix like the following shape

If p = [p1 p2 p3 ... pn]^T which is n-by-1. How to create the following shape?

P = [p1 0;0 p1;p2 0;0 p2;p3 0;0 p3;...;pn 0;0 pn]

which is 2n by 2.

Upvotes: 0

Views: 42

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

Let p be defined, for example, as

p = [10 20 30 40];

Some possibilities:

  1. Using sparse:

    P = full(sparse([1:2:2*numel(p) 2:2:2*numel(p)], repelem([1 2], numel(p)), [p p]));
    
  2. Using just assignment indexing:

    P = zeros(2*numel(p), 2);
    P((1:2:2*numel(p)).' + [0 2*numel(p)+1]) = [p p];
    
  3. Using conv2:

    t = zeros(2*numel(p)-1, 1);
    t(1:2:end) = p;
    P = conv2(t, eye(2))
    

Upvotes: 2

Mad Physicist
Mad Physicist

Reputation: 114578

A very straightforward way would be:

q = zeros(2 * size(p))
q(1:2:end, 1) = p
q(2:2:end, 2) = p

More concisely, you can use kron:

q = kron(p, eye(2))

Upvotes: 2

Related Questions