Frank liu
Frank liu

Reputation: 43

What does this mean in Matlab: x=x(: , N)

I have seen this in others code and cannot understand what this means x=x(: , N) where x is a 2D array, N is a 1D array

Here are some examples

test = [1,2;3,4];
ttt = [1,1,1,1 ,2,2,2,2];
test = test(:,ttt);

The result is:

1   1   1   1   2   2   2   2

3   3   3   3   4   4   4   4

and

test = [1,2;3,4];
ttt = [1,1,1,1 ,1,1,1,1];
test = test(:,ttt);

The result is:

1   1   1   1   1   1   1   1

3   3   3   3   3   3   3   3

Thank you!

Upvotes: 3

Views: 1131

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112729

test(:,ttt) means: from matrix test take all rows (:), and the columns indicated by ttt.

So in your first example (ttt = [1,1,1,1,2,2,2,2]) you take the first column of test four times, then the second column four times. In the second example (ttt = [1,1,1,1,1,1,1,1]) you take the first column of test eight times.

For more information about indexing in Matlab, see here.

Upvotes: 4

IKavanagh
IKavanagh

Reputation: 6187

Primarily the notation x(:, N) is used to index specific columns in x that are given by N as in

>> x = zeros(3, 3);
>> x(:) = 1:9;
>> N = [1 3];
>> x(:, N)
ans =

     1     7
     2     8
     3     9

Here : indexes all of the rows in x and N is used to index the columns 1 and 3 in x. Your example is an extension of this.

So in the next example because 1 occurs multiple times it indexes (and returns) that column of x for every time it occurs. Hence, why we see the first column that contains 1 and 3 4 times.

>> x = [1 2; 3 4]
x =

     1     2
     3     4
>> N = [1 1 1 1];
>> x(:, N)
ans =

     1     1     1     1
     3     3     3     3

This final example in your question is another extension of this, except this time we also have 2's in N so we see the second column with 2 and 4 replicated.

>> x = [1 2; 3 4]
x =

     1     2
     3     4
>> N = [1 1 1 1 2 2 2 2];
>> x(:, N)
ans =

     1     1     1     1     2     2     2     2
     3     3     3     3     4     4     4     4

Next when we add in the = we are assigning the output of x(:, N) to x overwriting what was previously in it

>> x = x(:, N)
ans =

     1     1     1     1     2     2     2     2
     3     3     3     3     4     4     4     4

Upvotes: 4

Related Questions