1

I want to create an array according to row number and column number.

For example :

row_number   Column_number    Value
  1               1            5
  3               2           10
  4               6            4
  7               5           66

The array should look like :

A=


 5   0   0   0   0   0
 0   0   0   0   0   0
 0  10   0   0   0   0
 0   0   0   0   0   4
 0   0   0   0   0   0
 0   0   0   0   0   0
 0   0   0   0  66   0

Otherwise it will print zero.

m7913d
  • 10,244
  • 7
  • 28
  • 56
Md. Abdur Rahim
  • 129
  • 1
  • 1
  • 10

1 Answers1

6

3 possible methods to this regularly asked question:

1. Using the sub2ind function

A = zeros(max(row_number), max(Column_number));
idx = sub2ind(size(A),row_number, Column_number);
A(idx) = Value;

2. Calculating the linear indices manually

A = zeros(max(row_number), max(Column_number));
idx = row_number(:,1) + (Column_number(:,2)-1)*size(A,1)
A(idx) = Value;

3. Use a sparse matrix

sparse(row_number, Column_number, Value)

And then call full on that if you want to convert it to a regular matrix

Dan
  • 45,079
  • 17
  • 88
  • 157