0

I need a 3D matrix in matlab, I have another 2D matrix (7570x3) too, The 3D matrix should have zero number except of all dimensions in 2D matrix that should have 1 value. How can I do that.

i.e. 2D matrix (1,:) = 28,64,27 then 3d(27,64,27) should be 1

how can i do that?

0

2 Answers 2

1

Assuming a is your 2-d matrix, and b is the 3-d one, use sub2ind as follows:

b=false(max(a));  % preallocate memory for a logical zeros matrix b
b(sub2ind(size(b),a(:,1),a(:,2),a(:,3))) = 1;

Check to see what max(a) gives you to see if you can host a 3-d matrix of size(max(a) to begin with. Since you are interested in a logcial matrix (ones and zeros), the size of that matrix in memory is the same as the # of elements, n*m*l, so a 1000x1000x1000 will take 1 GB.

Note, it very well may be that b is very sparse, if that is the case you can refer to this thread to see how to deal with it. Know that at the moment, and to the best of my knowledge, matlab doesn't support 3d sparse matrices. So you may want to check this option from the FEX. When I think of it, you already have a sparse look-up table of the 3D matrix! it is just your 2D matrix you started with...

2
  • see my edit regarding the full matrix use for the case it is a logical matrix. I've used false to preallocate instead of zeros. this is more memory efficient.
    – bla
    Nov 30, 2013 at 9:07
  • Thanks for you comment, I changed your code to make it make in for non-integer matrix too
    – Ehsan
    Dec 6, 2013 at 4:56
0

Thanks a lot @natan

for non-integer matrix also can use:

b=false(floor(max(a)));  % preallocate memory for a logical zeros matrix b
b(sub2ind(size(b),floor(a(:,1)),floor(a(:,2)),floor(a(:,3)))) = 1;

or use round function:

b=false(round(max(a)));  % preallocate memory for a logical zeros matrix b
b(sub2ind(size(b),round(a(:,1)),round(a(:,2)),round(a(:,3)))) = 1;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.