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$>
References: <k00d1c$13u$> <k00e6v$4fi$> <k00fpn$94r$>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
X-Trace: 1344523335 19643 (9 Aug 2012 14:42:15 GMT)
NNTP-Posting-Date: Thu, 9 Aug 2012 14:42:15 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: comp.soft-sys.matlab:776056

"mono" wrote in message <k00fpn$94r$>...
> "Justin Ashmall" <> wrote in message <k00e6v$4fi$>...
> > > 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);

% Bruno