I need to use information from two columns in a matrix, to build a matrix using information from a third column.

2 views (last 30 days)
I wish to build a 4x6 matrix from information given as a matrix. The given matrix is 24x3, the first column has numbers, only four numbers, repeated over and over. The second column has six distinct IDs repeated four times. The final column contains data, which is used to build my final matrix.
MatrixA=[ 1 96310 1.1
2 96311 1.2
3 96312 1.3
4 96313 1.4
1 96314 1.5
2 96315 1.6
3 96310 1.7
4 96311 1.8
1 96312 1.9
2 96313 2.0
3 96314 2.1
4 96315 2.2
1 96311 2.3
2 96312 2.4
3 96313 2.5
4 96314 2.6
1 96315 2.7
2 96310 2.8
3 96311 2.9
4 96312 3.0
1 96313 3.1
2 96314 3.2
3 96315 3.3
4 96310 3.4]
My desired end result is:
[1.1 2.3 1.9 3.1 1.5 2.7
2.8 1.2 2.4 2 3.2 1.6
1.7 2.9 1.3 2.5 2.1 3.3
3.4 1.8 3 1.4 2.6 2.2]
The numbers have all been made up, but the concept is still the same. I need to somehow build a code which allows me to create that final matrix using information presented in the style of MatrixA.
I have been advised that apparently I could do this by making use of the functions unique, ismember and sub2ind . I have been playing around with this since Tuesday, still haven't been able to complete this.
  1 Comment
Jan
Jan on 19 Jul 2015
Edited: Jan on 19 Jul 2015
You forgot to reveal the wanted pattern. Why is the element (1,2) set to 2.3? Why is the element (2,1) set to 2.8? It is not reliable or efficient, when we guess what you want.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 19 Jul 2015
Edited: Stephen23 on 20 Jul 2015
[uid, ~, ididx] = unique(MatrixA(:,2));
result = accumarray([MatrixA(:,1), ididx(:)], MatrixA(:,3));
  3 Comments
Richard Lea
Richard Lea on 20 Jul 2015
Omg! It works perfectly! Can you please explain why the first line works, and where I can get more information about that. Thanks!

Sign in to comment.

More Answers (1)

Jan
Jan on 19 Jul 2015
Edited: Jan on 19 Jul 2015
A bold guess:
A = [ 1 96310 1.1; ...
2 96311 1.2; ...
3 96312 1.3; ...
4 96313 1.4; ...
1 96314 1.5; ...
2 96315 1.6; ...
3 96310 1.7; ...
4 96311 1.8; ...
1 96312 1.9; ...
2 96313 2.0; ...
3 96314 2.1; ...
4 96315 2.2; ...
1 96311 2.3; ...
2 96312 2.4; ...
3 96313 2.5; ...
4 96314 2.6; ...
1 96315 2.7; ...
2 96310 2.8; ...
3 96311 2.9; ...
4 96312 3.0; ...
1 96313 3.1; ...
2 96314 3.2; ...
3 96315 3.3; ...
4 96310 3.4];
ID = unique(A(:, 2));
Result = zeros(4, numel(ID));
for kID = 1:numel(ID)
match = (A(:, 2) == ID(kID));
Result(A(match, 1), kID) = A(match, 3);
end

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!