Vectorization of a for loop to increase speed
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Howard Wilton
el 25 de Nov. de 2022
Editada: Bruno Luong
el 25 de Nov. de 2022
I am looking to embed an logical expression in an equation. The code example below is to show the problem and is not a reflection of the underlying math I am trying to solve!
t_ = -1:0.1:1;
for t = t_
flag = (t > a); % a is a vector, defined seperately
res = t - a(flag(:));
end
For each value of t, I would get a vector
that has a length that corresponds to the number of logical 1s in
.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1206913/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1206918/image.png)
What I would very much like to do is eliminate the for loop and do something kind of like this,
t = -1:0.1:1;
res = t - a(t > a)(:) % i presume this looks AWFUL
And as a result i end up with a matrix with one dimension the size of length t and the other dimension the size of the number of logical 1s in
.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1206918/image.png)
Would welcome any ideas or comments.
1 comentario
Stephen23
el 25 de Nov. de 2022
Editada: Stephen23
el 25 de Nov. de 2022
"And as a result i end up with a matrix with one dimension the size of length t and the other dimension the size of the number of logical 1s in flag."
Your concept does not have a general solution because the "number of logical 1s in flag" could be different on each loop iteration, so that res vectors have different lengths, and therefore there is no such matrix (because each "other dimension" could be different).
Would you allow for padding of a matrix, or a 1xN vector, or use of a container array?
"The code example below is to show the problem and is not a reflection of the underlying math I am trying to solve!"
It would probably be much faster to explain the actual problem.
Respuesta aceptada
Bruno Luong
el 25 de Nov. de 2022
Editada: Bruno Luong
el 25 de Nov. de 2022
This returns a matrix, whose elements which do not satisfy the condition and was not computed in your orginal code are marked by NaN. Each row corresponds to one iteration of the original code
resmat = t_(:) - a(:).';
resmat(resmat<=0) = NaN;
% Move NaN towards the last columns
[~,js] = sort(isnan(resmat),2);
m = size(resmat,1);
resmat = resmat((js-1)*m+(1:m)')
0 comentarios
Más respuestas (0)
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!