Richard Tingle
Richard Tingle

Reputation: 17226

How can I extract a 1 dimentional row from a multidimentional matrix

I currently have a 3 dimensional matrix and I want to extract a single row (into the third dimension) from it by index (say matrix(2,1,:)). I initially anticipated that the result of this would be a 1 dimensional matrix however what I got was a 1 by 1 by n matrix. Usually this wouldn't be a problem but some of the functions I'm using don't like 3D matrices. For example see the problem replicated below:

threeDeeMatrix=rand(3,3,3);
oneDeeAttempt=threeDeeMatrix(1,1,:);
norm(oneDeeAttempt)

Which returns the error message:

Error using norm
Input must be 2-D.

This is because oneDeeAttempt is

oneDeeAttempt(:,:,1) =

    0.8400


oneDeeAttempt(:,:,2) =

    0.0700


oneDeeAttempt(:,:,3) =

    0.7663

rather than [0.8400 0.0700 0.7663]

How can I strip these extra dimensions? The only solution I can come up with is to use a loop to manually copy the values but that seems a little excessive.

Upvotes: 1

Views: 183

Answers (1)

Richard Tingle
Richard Tingle

Reputation: 17226

Using permute to rearrange the matrix

The solution (which I found in the final stages of asking this) is to use permute which rearranges the order of the dimensions (similar to a=a' for 2D matrices). Once the unit dimensions are last they are stripped from the matrix and it becomes 1 dimensional.

oneDee=permute(oneDeeAttempt,[3 1 2]) %rearrange so the previous third dimension is now the first
%the matrix is now 3 by 1 by 1 which becomes 3

Using squeeze to remove leading singleton dimensions

As pointed out by Luis Mendo squeeze will very simply remove these leading singleton dimensions without having to worry about which dimensions are non singleton

oneDee=squeeze(oneDeeAttempt);

Upvotes: 2

Related Questions