Why I get ans = logical 1

조회 수: 18 (최근 30일)
Mohamed Mahir
Mohamed Mahir 2020년 4월 3일
댓글: Mohamed Mahir 2020년 4월 3일
for i=1:100
x(i)=normrnd(0,1);
end;
A=x(:);
for i=1:100
if (A(i)<0.9557 & A(i) > 0)
Aq(i)=0.497;
elseif (A(i)>0.9957)
Aq(i)=1.493;
elseif (A(i)<-0.9957)
Aq(i)=-1.493;
else
(A(i)>-0.9957 & A(i) <0)
Aq(i)=-0.497;
end;
end;
sum=0;
for i=1:100
sum = (A(i)-Aq(i))^2+sum;
end;
Avg = sum/100
  댓글 수: 2
Geoff Hayes
Geoff Hayes 2020년 4월 3일
Mohamed - look closely at your else
else
(A(i)>-0.9957 & A(i) <0)
Aq(i)=-0.497;
end;
Should this be an elseif instead where (A(i)>-0.9957 & A(i) <0) is the condition?
Mohamed Mahir
Mohamed Mahir 2020년 4월 3일
Thank you very much it fixed it

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

채택된 답변

Steven Lord
Steven Lord 2020년 4월 3일
Another approach uses discretize.
>> A = randn(10, 1);
>> edges = [-Inf -0.9957 0 0.9957 Inf];
>> values = [-1.493, -0.497, 0.497, 1.493];
>> Aq = discretize(A, edges, values);
>> results = table(A, Aq)
If an element of A falls between (for example) edges(2) and edges(3) the corresponding element in Aq will be values(2).
I put the results in a table array so you can easily check that each element of Aq matches what it should be for the corresponding element of A.
  댓글 수: 1
Mohamed Mahir
Mohamed Mahir 2020년 4월 3일
Thank you that really helped me

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

추가 답변 (1개)

David Hill
David Hill 2020년 4월 3일
편집: David Hill 2020년 4월 3일
Much easier way:
A=normrnd(0,1,[100,1]);
[~,~,a]=histcounts(A,[-10,-.9957,0,.9957,10]);
b=[-1.493;-0.497;0.497;1.493];
Aq=b(a);
s=sum((A-Aq).^2);
Avg = s/100;

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by