How can I use values within a MATLAB matrix as indices to determine the location of data in a new matrix?

109 views Asked by At

I have a matrix that looks like the following.

enter image description here

I want to take the column 3 values and put them in another matrix, according to the following rule.

The value in the Column 5 is the row index for the new matrix, and Column 6 is the column index. Therefore 20 (taken from 29,3) should be in Row 1 Column 57 of the new matrix, 30 (from 30,3) should in Row 1 column 4 of the new matrix, and so on.

If the value in column 3 is NaN then I want NaN to be copied over to the new matrix.

2

There are 2 answers

2
Amro On BEST ANSWER

Example:

% matrix of values and row/column subscripts
A = [
 20  1 57
 30  1 4
 25  1 16
 nan 1 26
 nan 1 28
 25  1 36
 nan 1 53
 50  1 56
 nan 2 1
 nan 2 2
 nan 2 3
 80  2 5
];

% fill new matrix
B = zeros(5,60);
idx = sub2ind(size(B), A(:,2), A(:,3));
B(idx) = A(:,1);

There are a couple other ways to do this, but I think the above code is easy to understand. It is using linear indexing.


Assuming you don't have duplicate subscripts, you could also use:

B = full(sparse(A(:,2), A(:,3), A(:,1), m, n));

(where m and n are the output matrix size)

Another one:

B = accumarray(A(:,[2 3]), A(:,1), [m,n]);
0
Omid On

I am not sure if I understood your question clearly but this might help:

(Assuming your main matrix is A)

nRows = max(A(:,5));
nColumns = max(A(:,6));

FinalMatrix = zeros(nRows,nColumns);

for i=1:size(A,1)
    FinalMatrix(A(i,5),A(i,6))=A(i,3);
end

Note that above code sets the rest of the elements equal to zero.