# How to assign the values to a matrix?

17 visualizzazioni (ultimi 30 giorni)
Benson Gou il 26 Mag 2021
Modificato: Stephen23 il 26 Mag 2021
Dear All,
I have a zero matrix A whcih needs to be assigned values from an column vector B. The indecies of those elements are stored in a two-columns array C.
For example, B = [1 9 12 31], C = [1 4;3 6;5 2;6 3]. Then matrix A is =[0 0 0 1 0 0; 0 0 0 0 0 0; 0 0 0 0 0 9;0 0 0 0 0 0; 0 12 0 0 0 0;0 0 31 0 0 0].
Thanks a lot.
Benson
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Stephen23 il 26 Mag 2021
Modificato: Stephen23 il 26 Mag 2021
B = [1,9,12,31];
C = [1,4;3,6;5,2;6,3]
C = 4×2
1 4 3 6 5 2 6 3
A = zeros(6,6);
% assign those values:
X = sub2ind(size(A),C(:,1),C(:,2));
A(X) = B
A = 6×6
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 12 0 0 0 0 0 0 31 0 0 0
For comparison:
[0 0 0 1 0 0; 0 0 0 0 0 0; 0 0 0 0 0 9;0 0 0 0 0 0; 0 12 0 0 0 0;0 0 31 0 0 0]
ans = 6×6
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 12 0 0 0 0 0 0 31 0 0 0
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Audio and Video Data in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by