2
votes

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
Have you tried anything at all? With all due respect, you cannot just ask questions expecting people to give you code for your requirements :)rgamber
I did make some attempts prior to posting but I judged that they were sufficiently off-course that they would not help answerers, or future readers of this question. Should I have expressed my question in more general terms, e.g. without providing an image of my own data set? The help center says "You should only ask practical, answerable questions based on actual problems that you face."user1205901 - Reinstate Monica
@user1205901: look up sub2ind in the documentationAmro

2 Answers

1
votes

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]);
1
votes

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.