1
votes

I want to reduce a two dimensional matrix to row vector.

But using reshape with large matrices is really slow. The other alternative is to use colon, but i want matrix's transpose to be colon and not the matrix itself.

e.g.

A=magic(3)

A =

     8     1     6
     3     5     7
     4     9     2

A(:) will stack up all the columns one by one. but i am looking for something like this:

AA=A(2:3,:)';

and then reshape or colon AA instead of A.

The issue is i dont want to define additional variable like AA.

Is there anyway to reduce dimension of two dimensional matrix without reshape?

2
So why not just use A(2:3,:)' (or A(2:end,:).') without assigning it to a variable?Luis Mendo
I suspect it's not the reshape that takes time, but the need to copy the reshaped matrix into a different memory location.Shai
@LuisMendo, I guess because the OP wants it as a one-dimensional array in the end.A. Donda
@A.Donda Got it. ThanksLuis Mendo

2 Answers

1
votes

You can avoid the additional variable by linear indexing. For your example:

A([2 5 8 3 6 9])

which gives

3  5  7  4  9  2

What's happening here is that you treat A as if it was already transformed into a vector, and the elements of this one-dimensional array are accessed through indices 1 through 9. Using the colon is a special case of linear indexing, A(:) is the same as A(1 : end).

Figuring out the right linear indices can be tricky, but sub2ind can help with that.

It is possible that this slightly speeds up the code, mainly because (as @Shai wrote) you avoid writing data to an intermediate variable. I wouldn't expect too much, though.

0
votes

Try looking at subsref. For your example, you could use it as follows:

subsref(A',struct('type','()','subs',{{2:3,':'}}))

Update: I misunderstood the original question; I thought the OP wanted to select rows from 2:3 from the transposed A matrix keeping the columns as is. I will keep the previous answer in case it could be useful to others.

I think he/she could use the following to slice and flatten a matrix:

subsref(A(2:3,:)', struct('type','()','subs',{{':'}}))

This would give as output:

[3 5 7 4 9 2]'