user30609
user30609

Reputation: 264

Extracting data from 3d matrix

I have got a 3d matrix in the following form: 3x3x46

Is there a simple way that I can extract the a matrix with the 3rd row and first two columns?

For the example here which is 3x3x3 I would like to extract

0.2710    0.5965
0.0280    0.3255
0.2285    0.4695

Here is a sample:

val(:,:,1) =

   -0.0492    0.6831    0.1291
   -0.4870    0.2893    0.2642
    0.2710    0.5965    0.8940


val(:,:,2) =

   -0.2316    1.4371    2.5806
   -2.4170    1.2168    6.4721
    0.0280    0.3255    0.0730


val(:,:,3) =

   -0.0881    0.9226    0.3146
   -1.0027    0.8638    1.0925
    0.2285    0.4695    0.6715

Upvotes: 0

Views: 381

Answers (2)

Dev-iL
Dev-iL

Reputation: 24169

Let's dissect what you're asking:

a matrix with the 3rd row

val(3, ?, ?)

and first two columns

val(3, 1:2, ?)  % or [1,2]

As for the 3rd index, you want to do this for all "slices", so you should use :, which means "all" in this context:

val(3, 1:2, :)

As explained by obchardon, this results in a 1×2×3 array, whereas you wanted a 3×2(×1) - so we need to reorder the dimensions:

out = permute( val(3, 1:2, :), [3,2,1] );

Upvotes: 2

obchardon
obchardon

Reputation: 10792

You can use a classic linear index:

extract = val(3,1:2,:)

But of course it will produce a 1x2x3 matrice, with a leading singleton dimension. You can remove the singleton dimension with:

extract = squeeze(val(3,1:2,:))

En finally transpose your result to obtain the expected output:

extract = squeeze(val(3,1:2,:)).'

Upvotes: 1

Related Questions