سؤال

I have an MxN matrix and I want a column vector v, using the vector s that tells me for each row in the matrix what column I will take.

Here's an example:

Matrix =
[  4  13  93  20  42;
  31  18  94  64  02;
   7  44  24  91  15;
  11  20  43  38  31;
  21  42  72  60  99;
  13  81  31  87  50;
  32  22  83  24  04]    

s = [4 4 5 4 4 4 3].'

And the desired output is:

v = [20 64 15 38 60 87 83].'

I thought using the expression

Matrix(:,s)

would've work but it doesn't. Is there a solution without using for loops to access the rows separately?

هل كانت مفيدة؟

المحلول

It's not pretty, and there might be better solutions, but you can use the function sub2ind like this:

 M(sub2ind(size(M),1:numel(s),s'))

نصائح أخرى

You can also do it with linear indexing, here is an example:

M=M'; s=s';
M([0:size(M,1):numel(M)-1]+s)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top