How to set ranges for 2 different variables in the same loop?

I have a set of x and y values and I need to isolate and substitute the values which are within the range to a formula that I've already typed out, but it keeps coming up with the "Operands to the || and && operators must be convertible to logical scalar values."
This is the loop section of code =
while ((x < 40) & (x > 15) && (y < 25) & (y > 5))
deltaLdeltax = ((-(40 - x))/sqrt(((40-x)^2)+((y-10)^2)))+((x-15)/sqrt(((x-15)^2)+((y-25)^2)))+((x-10)/sqrt(((x-10)^2)+((y-5)^2)))
deltaLdeltay = ((y-10)/sqrt(((40-x)^2)+((y-10)^2)))+((-(25-y))/sqrt(((x-15)^2)+((y-25)^2)))+((y-5)/sqrt(((x-10)^2)+((y-5)^2)))
end

 채택된 답변

Alex Sune
Alex Sune 2019년 5월 20일
편집: Alex Sune 2019년 5월 20일
You don't need a loop:
x = randi(100,1,100);
y = randi(100,1,100);
idx = ((x < 40) & (x > 15) & (y < 25) & (y > 5));
x = x(idx);
y = y(idx);
deltaLdeltax = ((-(40 - x))./sqrt(((40-x).^2)+((y-10).^2)))+((x-15)./sqrt(((x-15).^2)+((y-25).^2)))+((x-10)./sqrt(((x-10).^2)+((y-5).^2)));
deltaLdeltay = ((y-10)./sqrt(((40-x).^2)+((y-10).^2)))+((-(25-y))./sqrt(((x-15).^2)+((y-25).^2)))+((y-5)./sqrt(((x-10).^2)+((y-5).^2)));

댓글 수: 4

madhan ravi
madhan ravi 2019년 5월 20일
편집: madhan ravi 2019년 5월 20일
Alex find() is not necessary in the line idx, direct logical indexing is more efficient.
Thanks Madhan. I know it, but I think it is better to understand what the code is doing for someone who is trying to do it with a loop. (changed anyway ;))
Thanks for your help! Sorry I'm not so confident with my matlab skills so I'm not sure what the x = randi(100,1,100); and the y = randi(100,1,100) is supposed to do in this section. What does this do?
It is just an example for x and y (row vectors of random numbers between 1 and 100). You have to use your x and y variables.

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

추가 답변 (1개)

KSSV
KSSV 2019년 5월 20일
while ((x < 40) && (x > 15) && (y < 25) && (y > 5))
deltaLdeltax = ((-(40 - x))/sqrt(((40-x)^2)+((y-10)^2)))+((x-15)/sqrt(((x-15)^2)+((y-25)^2)))+((x-10)/sqrt(((x-10)^2)+((y-5)^2)));
deltaLdeltay = ((y-10)/sqrt(((40-x)^2)+((y-10)^2)))+((-(25-y))/sqrt(((x-15)^2)+((y-25)^2)))+((y-5)/sqrt(((x-10)^2)+((y-5)^2)));
end

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2019년 5월 20일

댓글:

2019년 5월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by