# Iterating over non-zero elements of a sparse ITensor

edited

Forgive me if I'm missing something obvious, but is there a simple way to iterate over all non-zero elements of an ITensor?

Something like:

ITensor T = ITensor(...);
for (std::vector< IndexVal > ivals : T) {
...
}


This would get me the set of IndexVal addressing all elements of the tensor in no particular order, just like that output we get when we use PrintData(T). This would be useful to study the structure and sparsity of the tensor, or do some manual element-wise operations.

I know of ITensor::visit(), but it doesn't seem to be possible to get the actual IndexVal out of that, just the value of the element.

selected by

Good suggestion, thanks. I think this is a feature we should definitely have, so I just added it! (You'll have to pull the latest version of ITensor to get it.)

What I added is a function called iterInds which you in a range-based for loop, which gives the behavior you asked about.

Here is a sample code using it:

auto i = Index("i",2);
auto j = Index("j",3);
auto k = Index("k",4);

auto is = IndexSet(i,j,k);

auto T = randomTensor(i,j,k);

for(auto it : iterInds(T))
{
Print(it[0]);
Print(it[1]);
Print(it[2]);
Print(T.real(it));
println();
}

PrintData(T);

commented by (240 points)
Perfect! It's working like a charm. This will be super helpful.

Thank you so much for the speedy update! :)