Here is my code. How can I reduce that time without changing the result?
clear all;clc;close all;
L=1000;
c = randn(1,1000000);
cont3 = 1;
while cont3 < length(c)+1
if(abs(c(cont3)) < 1 || abs(c(cont3)) > 10)
c(cont3) = randn(1);
cont3 = 0;
end
cont3 = cont3+1;
end
c;

 채택된 답변

Jon
Jon 2020년 11월 16일
편집: Jon 2020년 11월 16일

0 개 추천

You can operate on the entire vector using for example
a(a<1) = randn
So you could make a loop something like
while any(a<1) || any(a>10)
a(a<1) = randn(sum(a<1),1)
a(a>10) = randn(sum(a>10),1)
end

댓글 수: 5

Mr.Chandler
Mr.Chandler 2020년 11월 16일
New randn value(n) must provide the condition ( 1 < abs(n) < 10 ) too.
Jon
Jon 2020년 11월 16일
편집: Jon 2020년 11월 16일
while any(a<1) || any(abs(a)>10)
condition1 = a < 1;
a(condition1) = randn(sum(condition1),1);
condition2 = abs(a) > 10;
a(condition2) = randn(sum(condition2),1);
end
Mr.Chandler
Mr.Chandler 2020년 11월 16일
I tried the last updated version of your suggestion. However, the values should be in the interval [-10,-1]U[1,10]. In your code, condition = a<1 contains all the values which are less then 1. But it is not okay with the condition. Because, while <1 it contains also [-10,-1] interval but it doesn't need to be changed.
Jon
Jon 2020년 11월 16일
Sorry I didn't look at your specification carefully. Anyhow you should be able to modify
while any(abs(a)<1) || any(abs(a)>10)
condition1 = abs(a) < 1;
a(condition1) = randn(sum(condition1),1);
condition2 = abs(a) > 10;
a(condition2) = randn(sum(condition2),1);
end
Mr.Chandler
Mr.Chandler 2020년 11월 16일
Thanks a lot. This solved my problem exactly.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Surrogate Optimization에 대해 자세히 알아보기

제품

릴리스

R2018a

질문:

2020년 11월 16일

편집:

2020년 11월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by