Efficient access to matrix elements

For instance I have the matrix:
A = [1 7 5 1 9;3 2 7 4 1]'
My question: What is the most efficient way to access the elements i column 2 with the same row number as the two 1's in column 1 (i.e. 3 and 4 in column 2)? I know how to solve it using "find", but is there a fast and more efficient way that works in the general case?

Answers (2)

This is my approach:
A = [1 7 5 1 9;3 2 7 4 1]'
Out = A(A(:,1) == 1, 2)
Out =
3
4
The logic is to search for the rows in the first column that are equal to 1, and then retrieve the second column value in each of the first columns that meet that criterion.
The most efficient way depends very much upon which MATLAB release you are using, and upon the size of the matrix, and upon the amount of memory you have available, and upon how big your primary cache is, and what cache-line size your hardware is using, and upon the speed of your memory, and upon the speed of your CPU, and upon which instruction sets it supports, and upon your Northbridge and Southbridge, and upon whether there is any possibility at all that there might be NaN in the matrix, upon whether you can reserve a CPU for yourself or if you have to share it with other tasks; and a large number of other details.
Accordingly, you will need to test out all of the possibilities yourself on your own system with representative matrices in order to determine what the most efficient way is. Chances are that the time you spend researching the possibilities and developing test suites and debugging and analyzing the data will add up to far far far more than you would lose by merely using a "pretty good but maybe not the most efficient" implementation.

Categories

Asked:

on 20 Mar 2016

Answered:

on 20 Mar 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!