Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Extract Matrix values using vector values

10 views
Skip to first unread message

Cyrille

unread,
Dec 11, 2009, 11:37:21 AM12/11/09
to
Hi,

I am trying to extract values from a matrix contained at the position
dictated in a vector.
So if I have a matrix and vector with values:
mymatrix = [3 4 5 6 7; 2 3 4 5 6]
myvector = [2; 4]

I want a resulting vector:
result = [4; 5]

I can do it using a for loop:
for i=1:2;
result(i)=mymatrix(i,myvector(i));
end;

Is there a more elegant and efficient way of doing this?

Cyrille MdC

Steve Bellenot

unread,
Dec 11, 2009, 12:11:39 PM12/11/09
to
In article <fba4908c-d446-4be4...@g7g2000yqa.googlegroups.com>,

It took me a minute to see what wanted. Look at
newmatrix = mymatrix'
newvector = myvector + 5*(0:1)'
newmatrix(newvector)

5 is the of rows in newmatrix or columns in mymatrix.
1 is one less then the number of entries in myvector.
--
Steven Bellenot http://www.math.fsu.edu/~bellenot
Professor and Associate Chair phone: (850) 644-7405
Department of Mathematics office: 223 Love
Florida State University email: bellenot at math.fsu.edu

Tim Wescott

unread,
Dec 11, 2009, 1:23:41 PM12/11/09
to

It would seem that your myvector, having only two entries, would only
specify one location in the matrix: mymatrix(myvector(1), myvector(2)).

If you specified

myvector = [[1 2]' [5 1]'];
then

mymatrix(myvector(:, 1), myvector(:, 2))

would cough up mymatrix(1, 5) and mymatrix(2, 1).

--
www.wescottdesign.com

Message has been deleted

Cyrille

unread,
Dec 11, 2009, 4:04:17 PM12/11/09
to
On Dec 11, 6:11 pm, belle...@math.fsu.edu (Steve Bellenot) wrote:
> In article <fba4908c-d446-4be4-a2d1-4df099aff...@g7g2000yqa.googlegroups.com>,

Thank you Steven,

That works - it definitely took me a few minutes to understand the
strategy you outlined.
I really enjoyed your idea about multiplying the incremental vector
(0:2) by the transposed matrix' row number. I didn't realize you could
access values by wrapping through the matrix like this. Understanding
your algorithm gave me a buzz - thank you again.
I'm applying it to a 6000x30 matrix. Although I originally thought
your strategy might not be as fast as the for loop option, I timed
both methods and yours takes 63ms to my 172ms. Almost a third the
time!

Have a great day and weekend!
Cyrille

0 new messages