Mathematica Beginner's Mathematica Q: {4,4,1} to {4,4} ?

  • Thread starter Thread starter hadron23
  • Start date Start date
  • Tags Tags
    Mathematica
AI Thread Summary
To convert a 3D matrix of dimensions {4, 4, 1} to a 2D matrix of dimensions {4, 4} in Mathematica, the recommended method is to use the part extraction syntax. For example, using A[[All, All, 1]] effectively selects all elements from the first two dimensions while retaining only the first slice of the third dimension. Alternatively, the syntax A[[1;;, 1;;, 1]] can also achieve the same result, demonstrating that ranges can be specified similarly to MATLAB but with a different notation. The use of Map[Flatten, A] is another approach that flattens the innermost lists, resulting in the desired 2D structure.
hadron23
Messages
28
Reaction score
1
Hi,

I have just started using Mathematica mainly for its symbolic math abilities; however, I have run into a small problem that I don't know how to fix.

I have generated a matrix of dimensions:

Dimensions[A] = {4,4,1}

And I need to convert this to a matrix of dimensions:

Dimensions[A] = {4,4}

This is easy in Matlab (just A(:,:,1) = []) but I don't have a clue how to do it in Mathematica.

Thanks!
 
Physics news on Phys.org
In[1]:= A=Table[x,{4},{4},{1}]
Out[1]= {{{x},{x},{x},{x}},{{x},{x},{x},{x}},{{x},{x},{x},{x}},{{x},{x},{x},{x}}}

In[2]:= Dimensions[A]
Out[2]= {4,4,1}

In[3]:= newA=Map[Flatten,A]
Out[3]= {{x,x,x,x},{x,x,x,x},{x,x,x,x},{x,x,x,x}}

In[4]:= Dimensions[newA]
Out[4]= {4,4}
 
Here's another example which is closer to the MATLAB syntax:

Code:
In[1]:= A=Array[x,{4,4,1}]
Out[1]= {{{x[1,1,1]},{x[1,2,1]},{x[1,3,1]},{x[1,4,1]}},
         {{x[2,1,1]},{x[2,2,1]},{x[2,3,1]},{x[2,4,1]}},
         {{x[3,1,1]},{x[3,2,1]},{x[3,3,1]},{x[3,4,1]}},
         {{x[4,1,1]},{x[4,2,1]},{x[4,3,1]},{x[4,4,1]}}}

In[2]:= A[[All,All,1]]
Out[2]= {{x[1,1,1],x[1,2,1],x[1,3,1],x[1,4,1]},
         {x[2,1,1],x[2,2,1],x[2,3,1],x[2,4,1]},
         {x[3,1,1],x[3,2,1],x[3,3,1],x[3,4,1]},
         {x[4,1,1],x[4,2,1],x[4,3,1],x[4,4,1]}}

Ranges in Part ( [[ ]] ) can be specified similarly to in MATLAB but with : replaced by ;;.
So the same result as Out[2] can also be produced using A[[1;;, 1;;, 1]] or A[[1 ;;, ;; -1, 1]] etc.
Note that you can't have ;; by itself -- for that you have to use All.
 

Similar threads

Back
Top