필터 지우기
필터 지우기

If condition for each matrix elements

조회 수: 3 (최근 30일)
Ying
Ying 2012년 2월 7일
Hi, I have a question about if function for matrix elements.
My code is here:
d1 = 1.5 + 0.3.*randn(100,1); %ball-bearing diameter
d2 = 1.2 + 0.5.*randn(100,1); %shaft diameter
c=abs(d1-d2);
if (0.2<c<0.5)
p(i)=1
else
p(i)=0
end;
mean(p)
Basically I want to compair each element in matrix c with 0.2 and 0.5. if the data falls in (0.2,0.5) value, accept it as 1. otherwise reject as 0.
MATLAB finds an error "Subscript indices must either be real positive integers or logicals." which I personally don't think is relevant to my problem. I would like to know how to compare each value within matrix c with 0.2 and 0.5.
I tried to put c as c(i), but MATLAB still finds an error.
Can somebody help me out here? I always seem to have trouble with matrix form.
Thanks a lot!
Ying

채택된 답변

Shiva Arun Kumar
Shiva Arun Kumar 2012년 2월 7일
There may be many ways to do this but does this solution work for you?
p=zeros(size(c));
p(intersect(find(c>.2)',find(c<.5)'))=1
  댓글 수: 2
Ying
Ying 2012년 2월 7일
Hi Shiva Arun Kumar,
Thanks for your answer. I run it in my MATLAB and it worked.
Your answer actually offered me a lot more options which I should refer to books and learn.
In case there is a way of using if statement, would it be possible
that you tell me which part I missed in my previous code?
The teacher was teaching about if function for accept/reject. I am
thinking it should be better if I follow whatever is taught in class.
Thanks again!
Ying
Walter Roberson
Walter Roberson 2012년 2월 7일
0.2<c<0.5 means ((0.2<c)<0.5) which compares the logical true/false result of 0.2<c to the value 0.5
Also, you are testing the entire vector at one time instead of testing one element at a time in a "for" loop.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Decomposition에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by