# How to quickly assign the values of a matrix using a given array?

1 visualizzazione (ultimi 30 giorni)
Benson Gou il 23 Mag 2021
Commentato: DGM il 24 Mag 2021
Dear All,
I have an array A which contains two columns of integers. I want to build a matrix B in the following way.
For example,
A = [2 9; 1 5; 8 3]
A = 3×2
2 9 1 5 8 3
The matrix B should be suilt as follows:
B = [0 1 0 0 0 0 0 0 -1 0; 1 0 0 0 -1 0 0 0 0 0; 0 0 -1 0 0 0 0 1 0 0]
B = 3×10
0 1 0 0 0 0 0 0 -1 0 1 0 0 0 -1 0 0 0 0 0 0 0 -1 0 0 0 0 1 0 0
How can I create matrix B for a goven A?
Thanks.
Benson
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

DGM il 23 Mag 2021
Modificato: DGM il 23 Mag 2021
Here is one way:
A = [2 9; 1 5; 8 3]
A = 3×2
2 9 1 5 8 3
s = [size(A,1) 10]; % you're going to have to specify the output width
B = zeros(s);
B(sub2ind(s,(1:s(1)).',A(:,1))) = 1;
B(sub2ind(s,(1:s(1)).',A(:,2))) = -1;
B % show the result
B = 3×10
0 1 0 0 0 0 0 0 -1 0 1 0 0 0 -1 0 0 0 0 0 0 0 -1 0 0 0 0 1 0 0
##### 2 CommentiMostra NessunoNascondi Nessuno
Benson Gou il 23 Mag 2021
Hi, DGM,
I run your code. it took 0.0107 second, much less than original 0.15 second. But when I tried to use sparse to reduce the CPU time futher, but it took 0.13 second. I want the final matrix B is sparse.
Thanks.
Benson
DGM il 24 Mag 2021
I really have no familiarity with handling sparse matrices or how to optimize for them. I'm sure someone else can though.

Accedi per commentare.

### Più risposte (1)

Walter Roberson il 23 Mag 2021
S = 10;
A = [2 9; 1 5; 8 3]
A = 3×2
2 9 1 5 8 3
(A(:,1) == (1:S))-(A(:,2) == (1:S))
ans = 3×10
0 1 0 0 0 0 0 0 -1 0 1 0 0 0 -1 0 0 0 0 0 0 0 -1 0 0 0 0 1 0 0
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.