If condition for each matrix elements
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个评论
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!