Miles
Miles

Reputation: 2527

Get 3D Matrix dimension as a Vector in Matlab

In Matlab, if I were to have a 3D Matrix as follows:-

>> T = rand(4,4,3)

T(:,:,1) =

    0.3214    0.0986    0.4552    0.4033
    0.2283    0.8989    0.7460    0.8627
    0.9535    0.5170    0.6831    0.6013
    0.1657    0.7017    0.9876    0.9445


T(:,:,2) =

    0.5260    0.2102    0.2393    0.9158
    0.8759    0.2099    0.5677    0.4351
    0.5829    0.5325    0.9171    0.7946
    0.5918    0.6938    0.0176    0.0641


T(:,:,3) =

    0.7209    0.7310    0.8726    0.0960
    0.3021    0.1482    0.0549    0.2180
    0.2190    0.4476    0.4889    0.5725
    0.7653    0.3743    0.9298    0.1413

And I wanted to obtain all of the elements in the dimensions (1,1,:), how would it be done?

I have tried the following:-

t = T(1,1,:)

But it yields:-

t(:,:,1) =

    0.3214


t(:,:,2) =

    0.5260


t(:,:,3) =

    0.7209

However, I wish to perform a vector product operation on the values as a vector, like so:-

t = [0.3214, 0.5260, 0.7209]
v2 = t*v'

and then perform some modifications to t, storing the resulting vector back into the 3D Matrix T.

I would like to do this in a vectorized manner if possible.

Upvotes: 3

Views: 647

Answers (2)

chappjc
chappjc

Reputation: 30579

reshape:

t = reshape(T(1,1,:),1,[]);

Or permute:

t = permute(T(1,1,:),[1 3 2])

Both options above give a row vector. For a column vector: t = reshape(T(1,1,:),[],1); and t = permute(T(1,1,:),[3 2 1]).

You do not need to match dimensions to write back (e.g. T(1,1,:) = v2; will suffice).

Upvotes: 4

Daniel
Daniel

Reputation: 36710

%get t, removing all singleton dimensions
t=squeeze(T(1,1,:))
%some operations
t=t*rand(1)
%writing t back
T(1,1,:)=t

Upvotes: 4

Related Questions