# Code optimization by way of selective computations

1 vue (au cours des 30 derniers jours)
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.
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

### 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 commentairesAfficher 2 commentaires plus anciensMasquer 2 commentaires plus anciens
Howard Wilton le 22 Nov 2022
Yeah. That is a good point. I did it again with just 1% of the flags set, but the overall processing was comparable to the unconditioned version. I shall have a look at sparse arrays. Thanks.

Connectez-vous pour commenter.

### Plus de réponses (1)

Torsten le 22 Nov 2022
Modifié(e) : Torsten le 22 Nov 2022
Ts = 1e-7; t = 0:Ts:1-Ts;
tic
s_t = exp(1i*2*pi*t(1:2:end));
toc
Elapsed time is 0.111464 seconds.
or if your condition is more complicated:
tic
s_t = exp(1i*2*pi*t(mod(1:length(t),2)==1));
toc
Elapsed time is 0.431624 seconds.
##### 0 commentairesAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by