COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### How to if-else in 1 line in matlab like C --- x = (d < D0)?20:30;---

• Email
• Follow

```I would like to do if-else in 1 line in matlab but I don't know if MATLAB has this feature.

My C program is:

x = (d < D0)?20:30;

which is equal to
if (d < D0)
x = 20;
else
x = 30;

Please suggest how can I do this for 1 line in matlab??? Thank you very much.
```
 0

See related articles to this posting

```On 4 Dez., 06:15, "Aui " <littlebearproj...@gmail.com> wrote:
> I would like to do if-else in 1 line in matlab but I don't know if MATLAB has this feature.
>
> My C program is:
>
> x = (d < D0)?20:30;
>
> which is equal to
> if (d < D0)
>    x = 20;
> else
>    x = 30;
>
> Please suggest how can I do this for 1 line in matlab??? Thank you very much.

why does everyone wants to make his code unreadable?

if (d < D0) x = 20; else x = 30;end;

or for this special case

x = (d < D0)*10+20;
```
 0

```Thank you Justus.

Actually, I want to apply on matrix and the code is just for example.

The real one is

F_mb = G./((D <= 500).*H1);
F_mb = G./((D > 500).*H2);

where D, G, H1 and H2 is matrix with the same size.

I just would like to combine them into a single line. Is that possible.
```
 0

```Well, actually, the above code is that I would like to avoid divided by zeros.

but the above code is still incorrect.

My goal is that I would like to divide G with H only the position that H element is not zeros so that will not produce divided by zero problem.

F_mb = G./((H1 ~= 0).*H1);

but in this case, even H1 is 0, it still divided by zeros.
```
 0

```In this thread you seem to be unclear as to what exactly you want.  Does this do it?

F_mb = H1~=0;
F_mb = G(F_mb)./H1(F_mb)

This *could* be done in one line, but it wouldn't be as efficient.
```
 0

```Hello, Matt Fig,

Thank you. It seems to produce what I want but the dimension of the result matrix change!!!! How can I keep the same dimension?

I applied your code for testing a small size matrix
F_mb = H1~=0;
F_mb = G(F_mb)./H1(F_mb)

-------------------

>> G = [2 2; 4 4];
>> H1 = [0 0; 10 10];
>> F_mb = H1~=0

F_mb =

0     0
1     1

>> F_mb = G(F_mb)./H1(F_mb)

F_mb =

0.4000
0.4000

------------------

What I expect the result should be
F_mb =
2                         2
0.4000              0.4000

Thank you
```
 0

```Well that does add a little bit of complication doesn't it?

% Data
G = [2 2; 4 4];
H1 = [0 0; 10 10];

% Engine
F_mb = G;
idx = H1~=0;
F_mb(idx) = G(idx)./H1(idx)
```
 0

```Hi Matt Fig,

Thank you so much. That's what I want (but I cannot do it myself ^^).
```
 0