%how to get elements out of matrix based on test
%find gets the elemenets whose value is not zero
X = [3 2 0; -5 0 7; 0 0 1; -4 0 6]

%returns row, col indices and value of elements in X that are NOT zero
[row,col,v] = find(X)
%how to get the set of row(n),col(n),n=1:length(row or col) elements?
%(if try to use row and col vectors like this X(row,col) get all
%combinations of the two vectors - the col_vec.*row_vec "product", not 
%match ups of the length(row or col) row(n),col(n)

%use linearidx = sub2ind(size(X),row,col) to get linear index to elements
%selected. sub2ind is vectorized so gives vector of the linear indices of 
%the elements row(n),col(n),n=1:length(row or col)
linearidx = sub2ind(size(X),row,col)
selectedX=X(linearidx)
%or
%selectedX=X(sub2ind(size(X),row,col)) %if don't need linear index anywhere
%else
%row, col, and selectedX are Nx1 vectors. selectedX=v.

%what do these do?
[row col val]=find(X<=5)
[row,col,v] = find(X>0)
%we can see that the row and column vectors have the indices of elements of
%X that meet the condition (as above), but all the values, v, reported are 
%now 1.
%this is because the find call is operating on the logical matrix that is
%output from the test of X, not on X itself.
%we get the selected elements of X the same way we did before (in this case
%we have to do this, in the first case it was redundant as v had the
%answer)
linearidx = sub2ind(size(X),row,col)
selectedX=X(linearidx)
%lines 22 and 23 are different realizations of same argument

%How about this?
[row,col,v] = find(X(X>0))
%row is a Nx1 column vector from 1 to N
%col is Nx1 column vector of 1s
%v has the selected elements (1:N) from the vector X. In this case we loose
%the references back to the original as the find operates on the Nx1 output
%of the call X(X>0) which has the elements of X that meet the test.

%do it with some random numbers - this will give different results each
%time it is run (the call to randn generates a new output on each call)
XX=randn(4,3)
XX(XX>0)
[row col val]=find(XX>0)
linearidx = sub2ind(size(X),row,col)
XXX=XX(sub2ind(size(XX),row,col))
%val is all 1s since is from the logical matrix from the test
%XXX=XX.
%here we keep the original locations in XX in row and col.

%if you want to repace all the elements of a matrix that meet a condition
%with a constant (value, NaN, inf). No indexing information returned.
X=randn(4,3)
X(X>0.1) = -1