In Fortran, is it possible to select certain parts of the an array by using some vector of logical values instead of the indices? For example like this:
iszero(1) = 0
iszero(2) = 1
iszero(3) = 0
sum0 = sum(iszero) !was sum0 = sum(iszero==0)
!mymatrix is arbitary is 3 times 3 array
mysubmatrix(1:sum0,1:sum0) = mymatrix(iszero==0,iszero==0)
call dtrmv('l','n','u',sum0,mysubmatrix(1:sum0,1:sum0),sum0,x(1:sum0)),1)
If this is not possible directly, is there an easy (fast) way to find the indices where iszero=0?
edit: I changed the example to present a more realistic case, in previous case I just changed some values to 100.0d0, where the elementwise handling would have been ok..
edit2: had one type on the fourth row of the code
will set all elements in mymatrix which are 0 to 100. If you are actually trying to do something a little more sophisticated than that, perhaps setting a matrix to have a ‘checkerboard’ of 1s and 0s you could try something like;
where m,n are the numbers of rows and columns in mymatrix. I haven’t tested this latter snippet, it’s just a suggestion to consider array subscript triplets sometimes.
EDIT
If you actually want to use one matrix (or vector) as the mask in the where statement and another in the assignment part, ie something like this:
then you have (I think) to ensure that
index_matrixhas the same size asmymatrix. In your case you might end up with a statement such as:again I haven’t tested this and I don’t expect that I’ve got the padded reshape quite right but you can probably figure out the details.
FURTHER EDIT
I’m now finding it difficult to follow the question. The statement
will assign the value 1 to sum, so the statement
will, at run time, be something like this:
and I’m not sure that the rhs and lhs conform properly for Fortran. Does this compile ? If it does, does it execute correctly (with array-bounds checking) ?
Are you trying to create
submatrixwhich holds only the 0 elements ofmymatrix? If so then I think you are going to have a hard time of it, for the general case. Unless you can define the locations of the elements you want to select in terms of either indices or a vector of subscripts or a subscript triplet, then I don’t see that you can make an array on the lhs from the array on the rhs.If the locations of the 0s are arbitrary then you might be able to do what you want by flattening the original array to rank-1 and creating a rank-1 subarray of that, but you would lose the correspondence between 2D locations and their 1D counterparts.
FINALLY
Don’t forget that you can, in Fortran 2003, use a pointer to refer to a sub-matrix defined by vector or triplet subscripts, for example
and then pass
pointer_to_arrayaround.