Stop Matlab from processing a 1xn matrix as a column vector

I am very frustrated with MATLAB right now. Let me illustrate this problem. I'll be using informal notation here.

I have a column cell vector called B

. Let it now B = {'A';'B';'C';'D'}

.

I want to have a matrix G

that is m-by-n and I want to replace the numbers in the G

corresponding elements B

... For example, letG

[4 3; 2 1]

Let's say I have a variable n

that says how many rows G

I want to retrieve.

When I do B(G(1:2,:))

I get what I want['D' 'C'; 'B' 'A']

However, if I do B(G(1:1,:))

, I get ['D';'C']

when I really want to get['D' 'C']

I am using 1:n

and I want it to have the same behavior for n = 1

as for n = 2

and n = 3

. Basically, G

is actually a matrix n

-by-1500 and I want to take the top rows n

and use it as the indices in B

.

I could use an if statement that wraps the result if n = 1

, but that seems unnecessary. Is there really no way to do it so that it stops treating my 1-by-matrix as if it were a column vector?

+3


source to share


3 answers


According to this post by Lauren Schure :

Indexing with a single array C = A (B) produces an output of size B if both A and B are not vectors.

When both A and B are vectors, the number of elements in C is the number of elements in B and with orientation A.



You are in the second case, hence the behavior you see.

+4


source


To make it work, you must support output with as many columns as in G

. To achieve this, you can do something like this -

out = reshape(B(G(1:n,:)),[],size(G,2))

      

Thus, for n = 1:



out = 
    'D'    'C'

      

With n = 2:

out = 
    'D'    'C'
    'B'    'A'

      

+1


source


I think this will only happen in the 1st case. By default, matlab will return a column vector, since that is the way the matrix is ​​stored. If you want a string vector, you can just use transpose. Well, in my opinion it should be fine when n> 1.

0


source







All Articles