0

I have a loop:

if A == 1
    A = 2;
end
if B == 1
    B = 2;
end
if C == 1
    C = 2;

etc... Now this of course takes ages to write, but if I write it like:

if A == 1 || B == 1 || C == 1
    A = 2; B = 2; C = 2;
end

it will change all of the parameters if any of them is equal '1' What I'd like is a simple loop where I can say that if A or B or C or... is equal 'X' than the new value of only the one that is equal to 'X' changes to the new value, without having to write it like I did in the first example. Thank you

zellus
  • 9,617
  • 5
  • 39
  • 56
kojikurac
  • 205
  • 2
  • 4
  • 11
  • What if more than one of them is equal to 'x'? None, one, some, or all of them can be equal to 'X'. Also, the code you posted does not show a loop. – Tim Jul 16 '11 at 16:08
  • 1
    thank you, this is what I'm asking, how can I get a loop which functions if none, one, some or all are equal to 'x' without having to state it as a separated 'if statement' – kojikurac Jul 16 '11 at 16:35

4 Answers4

7

Maybe if you group them in a vector, you can do:

params = [A B C];
params(params==1) = 2;
Amro
  • 123,847
  • 25
  • 243
  • 454
1

In case you can change your code in order to have one variable indicating the different cases, the switch statement offers an elegant method to solve your task.

switch yourNumber
    case 1
        A = 2;
    case 2
        B = 2;
    case 3
        C = 2;
    otherwise
        disp('unknown value');
end

Where yourNumber may be assigned the values 1,2 or 3.

zellus
  • 9,617
  • 5
  • 39
  • 56
  • Thank you for your help, but as (I quote): " That is, switch executes only the first matching case; subsequent matching cases do not execute." I wouldn't be able to apply the rule to every parameter. – kojikurac Jul 16 '11 at 16:44
0

if you write

if A == 1 || B == 1 || C == 1
    A = 2; B = 2; C = 2;
end

By any of these conditions all A, B and C will be 2! and its not the same! The best is to group them in a vector.

Ramtin
  • 1
0

I don't think you should use unreadable code, but technically, you can get it down to three lines with no ifs:

A = abs(sign(A - 1)) * A + (1 - abs(sign(A - 1)) * 2
(same for B and C)

Yes, it's insane, and as I said, I wouldn't recommend it...

user816098
  • 262
  • 3
  • 14