Access to for loop index
Logical indexing without for loop
Looping with indices that are not equally spaced
Is it possible to go through the elements of an array without resorting to length in a for loop?
Videos
The documentation in for() states:
for index = values ... endwhere
valueshas one of the following forms:
...
valArray: creates a column vector index from subsequent columns of arrayvalArrayon each iteration. For example, on the first iteration,index = valArray(:,1). The loop executes for a maximum ofntimes, wherenis the number of columns of valArray, given bynumel(valArray, 1, :). The inputvalArraycan be of any MATLAB data type, including a string, cell array, or struct.
Therefore, I assume there is a significant overhead and the compiler does not check whether 1:ksize == klist to exploit the faster implementation. In other words, per Eitan's comment, the JIT applies to the first two types of accepted values.
The whole problem is related to the following indexing task (column vs element):
tic
for m = 1:100000
for k = 1:ksize
klist(:,k);
end
end
toc
tic
for m = 1:100000
for k = 1:ksize
klist(k);
end
end
toc
Index column: ~2.9 sec
Index element: ~0.28 sec
You can see how klist(:,k) effectively slows down the faster loop indicating that the issue in for k = klist is related to the column indexing used in this case.
For additional details see this lengthy discussion on (inefficient) indexing.
My answer is speculation (because only Mathworks guys know the implementation of their product), but I think the first k loop is optimized to not create the actual array of indices, but to just scan them one by one, because it explicitely shows how the values are "built". The second k loop cannot be optimized, because the interpreter doesn't know beforehand if the content of the index array will grow uniformly. So, each time the loop starts, it will copy access the original klist and that's why you have the performance penalty.
Later edit: Another performance penalty might be from indexed access int the klist array, compared to creating the index values "on the fly."
As the title says. Is there a way to iterate through array in .txt file without using any for loops? To be more clear, I need to check if elements of that array belongs to interval without using any for loops at all, but I can't find how to do it, all solutions on the internet has for loops.