Code optimization by way of selective computations
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Howard Wilton
le 22 Nov 2022
Commenté : Howard Wilton
le 22 Nov 2022
I have the following code:
clc; clearvars;
Ts = 1e-1; t = 0:Ts:1-Ts
flag = mod(1:length(t),2)
s_t = exp(1i*2*pi*t)
I am looking to only execute the
computation only when the corresponding value for
is logical 1. I wish to do this without iterating as the final vector to process is
long and is about 97% zero values in the result.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1202953/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1202943/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1202958/image.png)
0 commentaires
Réponse acceptée
Jiri Hajek
le 22 Nov 2022
Hi, you need to convert your flags to logical array, initialize the results with zeros and then apply the function to the flagged positions like this:
flag = logical(mod(1:length(t),2));
s_t = zeros(size(t));
s_t(flag) = exp(1i*2*pi*t(flag));
3 commentaires
Jiri Hajek
le 22 Nov 2022
Yes, the logical indexing probably does add to the execution time, as basic functions are quite optimized... But you mentioned that your non-zeros should be only about 3% of the array size, whereas in this test you have 50% nonzeros... So the test dis not really fair, I think.
Perhaps you can also look at sparse arrays, but truth is, their usefullness is also limited by the fraction of zero elements.
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!