Removing the third matrix size

Suppose I have a matrix such that A(:,:,1)=[1,2,3;2,3,4] , A(:,:,2)=[3,4,5;4,5,6] .

As the easiest way to access and build vectors (1,2,3), (2,3,4), (3,4,5), (4,5,6). I tried to create B=[A(:,:,1);A(:,:,2)] , but I need a procedure for an arbitrary number A.

I hope this is not trivial, and I have formulated myself satisfactorily.

+6
source share
2 answers

Assuming the order doesn't matter, here's how you can do it for vectors of length 3:

 B = reshape(shiftdim(A,2), [], 3) plot(B') 

For vectors of arbitrary sizes, replace 3 with size(A,2)

+4
source

You have to think upright. This will allow you to use colon indexing:

 >> A(:,:,1) = [1,2,3;2,3,4].'; %'// NOTE: transpose of your original >> A(:,:,2) = [3,4,5;4,5,6].'; %'// NOTE: transpose of your original >> A(:,:) ans = 1 2 3 4 2 3 4 5 3 4 5 6 

Two-colon colon indexing works for any dimension A :

 >> A(:,:,:,:,1,1) = [1 2 3; 2 3 4].'; %' >> A(:,:,:,:,2,1) = [3 4 5; 4 5 6].'; %' >> A(:,:,:,:,1,2) = [5 6 7; 6 7 8].'; %' >> A(:,:,:,:,2,2) = [7 8 9; 8 9 0].'; %' >> A(:,:) ans = 1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 0 

Indexing columns in MATLAB is quite interesting and really powerful once you get it right. For example, if you use fewer colonies than the sizes in the array (for example, higher), MATLAB automatically merges the rest of the data in size equal to the number of a colon.

So, if A has 48 dimensions, but you index only 2 colons: you get a 2D array, that is, the concatenation of the remaining 46 dimensions in size 2 nd ,

In the general case: if A has dimensions N , but you only index the colon M ≤ N : you get an array M -D, that is, the concatenation of the remaining NM dimensions along size M th .

As long as you are free to define your A to contain vectors in columns rather than rows (you should advise everyone to do this, since almost everything in MATLAB is a little faster) is the fastest and most elegant way to do what you want.

If not, well then just reshape like Dan :)

+5
source

All Articles