Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: how to use a vector as an index for a matrix
Date: Thu, 9 Aug 2012 14:42:15 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 22
Message-ID: <k00i87$j5r$1@newscl01ah.mathworks.com>
References: <k00d1c$13u$1@newscl01ah.mathworks.com> <k00e6v$4fi$1@newscl01ah.mathworks.com> <k00fpn$94r$1@newscl01ah.mathworks.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
NNTP-Posting-Host: www-05-blr.mathworks.com
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: newscl01ah.mathworks.com 1344523335 19643 172.30.248.37 (9 Aug 2012 14:42:15 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 9 Aug 2012 14:42:15 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:776056

"mono" wrote in message <k00fpn$94r$1@newscl01ah.mathworks.com>...
> "Justin Ashmall" <juestan-matlabnews6h8@yahoo.co.uk> wrote in message <k00e6v$4fi$1@newscl01ah.mathworks.com>...
> > > I want to use a vector as index for a matrix. For example, t=[2,3], I want to point to the value in the matrix M at M(2,3). If I command as M(t), actually it points to M(2) and M(3). How can I use t to point to M(2,3)?
> > 
> > You want the sub2ind function to convert to a linear index.
> > 
> > In your example, this would do the trick:
> > 
> >  M( sub2ind(size(M), 2, 3) )
> > 
> > You could replace the 2 and 3 with (equal sized) vectors to get multiple values back.
> > 
> > Justin
> 
> Hi Justin,
> 
> Thanks for your reply. But I don't think it solves my problem. The thing is t is a vector, and its  size is not fixed. It makes trouble to use its value inside. t can be t=[2,3], can also be t=[2,3,4]. Of course when t=[2,3], the matrix M is 2 dimensional, and when t=[2,3,4], M is 3 dimensional. You suggested to use sub2ind, however it still needs t as put. Obviously, M(sub2ind(size(M),t)) is not working. Any further suggestion?

sub2indvec = @(s,t) 1 + [1 cumprod(s(1:end-1))]*(t(:)-1);
M(sub2indvec(size(M),t))

% Bruno