Code optimization by way of selective computations

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.

 채택된 답변

Jiri Hajek
Jiri Hajek 2022년 11월 22일
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

This definitely works, but the computation time ends up being longer... I thought that if I avoid the computaitons I could reduce overall processing time.
clc; clearvars;
Ts = 1e-7; t = 0:Ts:1-Ts;
tic
s_t = exp(1i*2*pi*t);
toc
Elapsed time is 0.174337 seconds.
tic
flag = logical(mod(1:length(t),2));
s_t = zeros(size(t));
s_t(flag) = exp(1i*2*pi*t(flag));
toc
Elapsed time is 0.732422 seconds.
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.
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.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Torsten
Torsten 2022년 11월 22일
편집: Torsten 2022년 11월 22일
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.

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품

릴리스

R2020b

태그

질문:

2022년 11월 22일

댓글:

2022년 11월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by