# Append a controlled Initialize in Qiskit

I would like to create a controlled initialize, I have the following code:

a = QuantumRegister(2,"a")
b = QuantumRegister(2,"b")
circuit = QuantumCircuit(a,b)
circuit.initialize(state)


and I would like to encode state only if qubit a and b are 1. I first tried with isometry but then I discovered there is a new simple method like this:

controlled_gate = StatePreparation(state).control()


the problem is that I can't understand how to append on the circuit and how to set the control qubits.

The way to append gate instances to a QuantumCircuit is with the append method.

circuit.append(controlled_gate, circuit.qubits)


Here is a full example with explanations:

You mentioned:

I would like to encode state only if qubit a and b are 1

As such, you can create two single-qubit registers $$a$$ and $$b$$; and a register for the state to encode:

from qiskit import QuantumCircuit, QuantumRegister

circuit = QuantumCircuit(QuantumRegister(1, "a"),
QuantumRegister(1, "b"),
QuantumRegister(2, "state"))


Then, in order to control on two qubits ($$a$$ and $$b$$), you need to set control(2).

from qiskit.circuit.library import StatePreparation
import numpy as np

state = [0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0]
controlled_gate = StatePreparation(state).control(2)


Finally, the append. The second parameter describe how to wire the gate, in this case circuit.qubits $$= [a, b, state_0, state_1]$$:

circuit.append(controlled_gate, circuit.qubits)
circuit.draw()

      a: ──────────────────────■──────────────────────
│
b: ──────────────────────■──────────────────────
┌─────────────────────┴─────────────────────┐
state_0: ┤0                                          ├
│  State Preparation(0,0.70711,-0.70711j,0) │
state_1: ┤1                                          ├
└───────────────────────────────────────────┘