Fastest alternative to |y = ones(size(x))| ?
8 views (last 30 days)
Show older comments
The profiler red flagged this line, in a small function that is called by an inner-loop computation:
...
if n == 0
y = ones(size(x));
else if n == 1
...
end
I must clarify that this line is not just pre-allocation! I really need the variable y to be the same shape as x and hold 1 in each element. Ideally x can be of any dimensions but if pressed I will admit it is unlikely to be anything but a scalar, vector, or 2D matrix.
I can think of so many possible alternatives, and the practical problem is mostly solved, so this question is mostly for curiosity's sake. I am interested in the fastest method and also in the analysis of why it is fastest. Any ideas?
Thanks, -naor
1 Comment
James Tursa
on 29 Jul 2016
Edited: James Tursa
on 29 Jul 2016
There really isn't much going on with that line, so I doubt you will be able to improve it much, if at all, with other formulations. The only advantage one formulation might have over another that I can think of is multi-threading in the background for large sizes. Is the profiler flagging this as dominating the runtime? What else is going on around that line?
Answers (2)
Walter Roberson
on 29 Jul 2016
My timings cannot distinguish between 1 + zeros(size(x)) vs ones(size(x)) . The hack of using 1 + 0*x is slower.
If you are doing that calculation in a tight loop, then that hints that you might be doing it with x the same size many times in a row. In that case, do the ones() once with the appropriate size, assign to a variable, and then copy from the variable inside the loop. If it is not always the same size within the inner loop but is a small number of sizes, you could keep a cache. You could possibly even pre-process your list of x values to find the distinct sizes, calculate for those sizes before the loop, and then copy out of the appropriate cell array location inside the loop.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!