If condition for each matrix elements

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Shiva Arun Kumar
Shiva Arun Kumar il 7 Feb 2012
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 Commenti
Ying
Ying il 7 Feb 2012
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 il 7 Feb 2012
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.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by