help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: no way for simple matrix lookup ?


From: Mike Miller
Subject: Re: no way for simple matrix lookup ?
Date: Sun, 1 May 2005 11:40:21 -0500 (CDT)

On Wed, 16 Jun 2004, Quentin Spencer wrote:

D. Goel wrote:

Mike, that doesn't work, your recipe below is the first thing I tried. Example, A = [1 3; 2 4]
b=c=[1 2].

The answer needed is [1 4], but both of your answers below give me [1
2 3 4].
Try this:
octave>d=A((b-1)*size(A,2)+c)
d =
   1     4


This thread from June is dealing with almost the same problem I presented yesterday. Quentin suggested that there ought to be a function for this. But...


On Wed, 16 Jun 2004, Etienne Grossmann wrote:


A = reshape (1:12, 3,4);

b = [2 3 1 2 3];
c = [4 1 2 3 4];

D = A(sub2ind (size (A),b, c))

D = diag (A(b,c))              # Don't do that


Etienne has a function, but it is "ind2sub" and not sub2ind. So the above should have read

D = A(ind2sub (size (A),b, c))

Thanks to Etienne for developing this function.  I found it here:

http://omni.isr.ist.utl.pt/~etienne/octave/mcompat.2000.04.04/1.mcompat/ind2sub.html

There is a sub2ind that does things the other way around.

I suggest that the ind2sub function can be made more general by allowing the 'c' vector (columns) to be a matrix. In my problem yesterday, I had a vector for rows and a matrix for columns. It was like this:

Suppose I have an N x M matrix X and I wish to extract particular elements from certain rows of X. I want to be able to provide a list of rows as a vector, and I want to provide the columns within rows as a matrix like this:

r = [1,2,5,4]';
C = [1,3;2,4;1,4;2,3]

  1  3
  2  4
  1  4
  2  3

So I want to extract rows 1,2,5,4 in that order, but I want to extract only columns 1,3 in row 1, columns 2,4 in row 2, columns 1,4 in row 5 and columns 2,3 in row 4.

I figured out that this will work for me:

X(r*ones(1,size(C,2))+size(X,1)*(C-1))

ind2sub could be extended to do this so that I could do it this way:

X(ind2sub(size(X),r,C))

for it to work properly, the output of ind2sub would have to have the same size as C. It currently puts out a row vector, I believe.

Mike

--
Michael B. Miller, Ph.D.
Assistant Professor
Division of Epidemiology and Community Health
and Institute of Human Genetics
University of Minnesota
http://taxa.epi.umn.edu/~mbmiller/



-------------------------------------------------------------
Octave is freely available under the terms of the GNU GPL.

Octave's home on the web:  http://www.octave.org
How to fund new projects:  http://www.octave.org/funding.html
Subscription information:  http://www.octave.org/archive.html
-------------------------------------------------------------



reply via email to

[Prev in Thread] Current Thread [Next in Thread]