Reputation: 215
I want to construct a 3D matrix of size = 80 * 80 * 2
based on a set of data:
1 4532 1257.0
1 4556 1257.0
1 4622 257.0
1 4633 257.0
2 7723 31.0
2 8024 31.0
2 8099 31.0
2 9800 31.0
2 8524 34.0
2 8525 34.0
2 8700 734.0
2 8701 734.0
What I'm doing now is: I first obtain two 80 * 80
2D matrices A
and B
and then concatenate them using cat(3, A, B)
:
Denote the above data be M
.
for i = 1 : size(M,1)
if (M(:,1)==1)
[r c]=ind2sub(M(:,2));
A = accumarray([r c], M(:,3));
elseif (M(:,1)==2)
[r c]=ind2sub(M(:,2));
B = accumarray([r c], M(:,3));
end
end
cat(3, A, B)
I am curious if there is any solutions that can build the 80*80*2
matrix merely by the linear index (the second column of my data) or any other simpler solution works for the purpose.
I appreciate for your help.
Upvotes: 1
Views: 302
Reputation: 14939
So, I'm assuming your example data is incorrect, and that all values in column 2 are less than n*n
, where nxn
is the size of the matrix (80x80 in your case).
If that's the case, the following two lines should do the trick.
out = zeros(n,n,2);
out((M(:,1)-1).*n^2+M(:,2)) = M(:,3)
If the second column contains values up to 2*n*n, and thus are the linear indices, then:
out = zeros(n,n,2);
out(M(:,2)) = M(:,3)
Upvotes: 1