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

  • Context: Mathematica 
  • Thread starter Thread starter hadron23
  • Start date Start date
  • Tags Tags
    Mathematica
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
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!
 
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.