2

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.

3
  • Have you tried anything at all? With all due respect, you cannot just ask questions expecting people to give you code for your requirements :) Commented Nov 10, 2014 at 3:48
  • 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." Commented Nov 10, 2014 at 4:11
  • @user1205901: look up sub2ind in the documentation Commented Nov 10, 2014 at 4:36

2 Answers 2

1

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

Will I need to convert my array from double to int in order to follow your recommendation?
no, as long the doubles represent valid subscripts (whole numbers greater or equal to 1). You cant for example index an array using a fraction: x = rand(1,10); x(1.3) (ERROR!)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.