How to do simple if statement without using if

15 ビュー (過去 30 日間)
wakakami
wakakami 2016 年 11 月 3 日
コメント済み: Image Analyst 2020 年 4 月 9 日
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
Mischa Kim 2016 年 11 月 3 日
Depends. What is between the if-end?

サインインしてコメントする。

回答 (3 件)

Star Strider
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
wakakami 2016 年 11 月 3 日
Appreciate the help! I'm probably being dumb, but my situation is:
If x < y, then I want z to equal x. But if x > y, then I want z = x-y.
So I think the above solution is impossible for this particular situation, since I don't want z to = 0 in cases where x<y?
Star Strider
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
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
yahya naja 2020 年 4 月 7 日
can anyone help i can do it with if but how to do it without it
  3 件のコメント
yahya naja
yahya naja 2020 年 4 月 8 日
thanks anyway i will use your logic and try to modify it
Image Analyst
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by