how can i vectorize this loop?
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
William Brannon
el 12 de Nov. de 2017
Respondida: Akira Agata
el 13 de Nov. de 2017
% x is a vector given in main program
function y = userfunction2(x,k)
x=y;
for i=i:k
y=userfunction(y);
end
5 comentarios
Respuesta aceptada
Walter Roberson
el 12 de Nov. de 2017
See fold()
2 comentarios
Walter Roberson
el 12 de Nov. de 2017
ShiftLeftAux = @(V) {ShiftLeft(V)}
t = cell(1,k); t{1} = {y});
t2 = fold(ShiftLeftAux, t);
result = t2{1};
Not nearly as clean as I would like.
This does not really vectorize the loop, though: it merely hides the loop into fold(), the same as if you had just written a routine that did the operation multiple times.
If you want actual vectorization you should instead be using circshift().
There is no way in MATLAB to say "vectorize this arbitrary linear code": there are only ways to get it to apply the linear code without you writing a visible for loop. The results are typically slower than using a for loop.
Más respuestas (1)
Akira Agata
el 13 de Nov. de 2017
Seems that you would like to do circshift ?
Your 'y = ShiftLeft(x)' seems equivalent to 'y = circshift(x,1)', like:
x = 1:10;
y = circshift(x,1);
Then, y becomes
>> y
ans =
10 1 2 3 4 5 6 7 8 9
If you want to shift k times, you should simply do 'y = circshift(x,k)'. Please see more detail on circshift documentation page .
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!