How to do simple if statement without using if
이전 댓글 표시
Another silly question, this is a small part of a bigger overall homework problem I've been having, but if I have a situation where I want to say:
if (x>y)
~~~~
end
is there a way of doing that without using an if statement? Appreciate any help!
댓글 수: 1
Mischa Kim
2016년 11월 3일
Depends. What is between the if-end?
답변 (3개)
Star Strider
2016년 11월 3일
I have no idea what you want to do, but something like this could work:
z = (x.*y) .* (x>y)
It uses implicit logical indexing, so for x<=y, ‘z’ is 0 since (x>y) is 0 (false), and for x>y, ‘z’ is x.*y, since x>y is 1 (true).
Experiment with it with your code to get the result you want.
댓글 수: 2
wakakami
2016년 11월 3일
Star Strider
2016년 11월 4일
My pleasure!
Not impossible at all:
z = x.*(x<y) + (x-y).*(x>y);
This leaves undefined x==y, that would be zero.
You can also create an anonymous function version:
z = @(x,y) x.*(x<y) + (x-y).*(x>y);
to use anywhere in your script, just as you would any other function.
Image Analyst
2016년 11월 3일
Use while:
temp = x
while (x>y)
~~~~
x = y-1; % Force exit of while loop
end
% Restore x to original value
x = temp;
But why not simply use "if"? What's wrong with if???
yahya naja
2020년 4월 7일
0 개 추천
can anyone help i can do it with if but how to do it without it
댓글 수: 3
Image Analyst
2020년 4월 7일
편집: Image Analyst
2020년 4월 7일
.png)
I don't know how they get $11.75. I get $11.56. Here is how you'd do it:
w = 2.25
d = 3.5
distanceBeyond1 = ceil(d - 1) % Remaining distance
theFare = round(5 + 2 * distanceBeyond1 + w * 0.25, 2)
You can see that you have $5 for the first 1 km, leaving 2.5 km left. But you count any part of a km as a full km, so the remaining distance gets rounded up to 3 with ceil(). At $2 per km, that is $2*3 = $6 for the distance between 1 and 3.5 km, so now we have $11 so far. Then the wait cost is 2.25 * $0.25 = $0.5625. Adding up you get $5 + $6 + $0.56 = $11.56.
yahya naja
2020년 4월 8일
thanks anyway i will use your logic and try to modify it
Image Analyst
2020년 4월 9일
If you figure out how they got $11.75 instead of $11.56, let us know because I'm just not seeing it. Maybe they did something they didn't state, like the price gets rounded up to the nearest $0.25 or something.
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!