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
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
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).
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