Borrar filtros
Borrar filtros

Adding elements to the ends of vectors inside a cell array of vectors

1 visualización (últimos 30 días)
Is there a way to add elements to the ends of vectors that are inside a cell array of vectors which would be faster than the following code that uses a for-loop?
x = rand(1,20);
i1 = [1,7,11];
i2 = [6,10,20];
xLower = [0.1 0.2 0.3];
xUpper = [100 200 300];
tic();
for r = 1:length(i1)
xRegion{r} = [xLower(r) x(i1(r):i2(r)) xUpper(r)];
end
toc();
xRegion

Respuesta aceptada

Eike Blechschmidt
Eike Blechschmidt el 29 de Jul. de 2021
You could use arrayfun:
arrayfun(@(l,i1,i2,u) [l x(i1:i2) u], xLower,i1,i2, xUpper, uniform, false)
This is untested but should be faster.
  8 comentarios
Eike Blechschmidt
Eike Blechschmidt el 1 de Ag. de 2021
Editada: Eike Blechschmidt el 1 de Ag. de 2021
You have to differentiate between allocating the cell array and allocating for the actual content of the cell array. Basically your cell array is just storing a bunch of pointers to the actual arrays of double you create in your for loop.
So it would only make sense to do the following which in your current example does not bring any benefit as i1 is quite small (I tried that on my machine):
xRegion = cell(size(i1))
I don't know a way to pre allocate memory for the created double arrays from your loop which would not involve a loop.
Depending on how you later processes the data it could could be worth trying just to use a pre-allocated doble array instead and set all not needed fields to nan. Again just gussing if that even does speed up your code.
arrSize = i2 - i1 + 3;
xRegion1 = nan(length(i1), max(i2 - i1 + 2));
for r = 1:length(i1)
xRegion1(r, 1:arrSize(r)) = [xLower(r) x(i1(r):i2(r)) xUpper(r)];
end
Mark Szlazak
Mark Szlazak el 2 de Ag. de 2021
Thanks for the explanation on this type of pre-allocation.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by