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

  • 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
Reply Aui 12/4/2009 5:15:19 AM

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
Reply Justus 12/4/2009 5:51:17 AM


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
Reply Aui 12/4/2009 6:02:05 AM

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
Reply Aui 12/4/2009 6:17:01 AM

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
Reply Matt 12/4/2009 7:01:24 AM

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
Reply Aui 12/4/2009 7:39:20 AM

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
Reply Matt 12/4/2009 10:48:03 AM

Hi Matt Fig,

Thank you so much. That's what I want (but I cannot do it myself ^^).
0
Reply Aui 12/4/2009 3:51:03 PM

7 Replies
319 Views

(page loaded in 0.049 seconds)

Similiar Articles:













7/30/2012 10:11:25 AM


Reply: