This question already has an answer here:
- Linspace using matrix input matlab 1 answer
Given an array like a = [ -1; 0; 1];
. For each a(i)
, I need to compute a linearly spaced vector with linspace(min(a(i),0),max(a(i),0),3);
, where each linspace-vector should be stored into a matrix:
A = [-1 -0.5 0;
0 0 0;
0 0.5 1];
With a for loop, I can do this like so:
for i=1:3
A(i) = linspace(min(a(i),0),max(a(i),0),3);
end
How can I achieve this without using loops?
One of the possible solutions is to use
arrayfun
that applies a function to each element of the array. You also want to convert your results into a matrix, since the output is in the cell array. Since the output of thearrayfun
is non-scalar, you have to turn off uniform output.Edit: I performed some testing using tic-toc method on 100000 long arrays. I found out, that the solution with
arrayfun
takes approx. 1.5 time longer than the one you suggested with for loops.The fastest approach would be to calculate what you need using matrix-vector operation. For example, if you only need to calculate
linspace
with 3 elements, you can use something like:You can generalize this method for any number of elements in linspace function (not necessarily just 3). Note that readability will suffer, as the volume of code will increase:
Note, that in this method I loop over the number of elements in each linspace, but not through the array
a
. With small j (like j=3 in your example) this will work way faster compared to the method with looping over the arraya
(if you consider large arrays likea=rand(100000,1)
).The fastest way I can think of is calculating the step-size, construct the vector from that using implicit binary expansion.
Timeit:
A couple of
timeit
results using (usetimeit(@SO)
and remove comments from the blocks to be timed):Then the times are:
arrayfun
: 2.6298 sTake
a = [ -1; 0; 1]
. Create the min / max array:Now use
interp1