Callum Richards
Callum Richards

Reputation: 27

How to execute this if statement correctly in MATLAB

I'm having an issue with the below code. I would like the code to perform the first statement if the condition is true. However, it seems to be only performing the second statement regardless of the conditions. is the line 'if delta<0.9843' incorrect?

delta = [0,0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.6, 4,4.4];
D = 22.441;
W = 9.843;
P = 65.27;
for i = delta
    if delta < 0.9843
    zdelta = ((P+0.08*P)*W*(W*D).^0.5)*(0.96*(delta/W)+(0.216/0.03)*(delta/W).^2);
    else
        zdelta = ((P+0.08*P)*W*(W*D).^0.5*(2.4*((delta/W)-0.03)));
        disp(zdelta)
    end
disp(zdelta)
end

Upvotes: 2

Views: 51

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Actually, you are mixing vectorized (operations performed matrix-wise) and non-vectorized approaches (operations performed on a single value at once). In your current configuration, if you test for delta < 0.9843, this is what you will get:

ans =

  1×12 logical array

   1   1   1   0   0   0   0   0   0   0   0   0

a logical array with 1 where the value is less than the threshold or 0 otherwise. Hence, your if condition will be performed on an array, not on a boolean variable, producing a result that is not very significant.

The computation you are trying to perform can be done in a vectorized way as follows:

D = 22.441;
W = 9.843;
P = 65.27;

delta = [0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.6, 4,4.4];
delta_min = delta < 0.9843;

delta_min_vals = delta(delta_min);
delta(delta_min) = ((P+0.08*P)*W*(W*D).^0.5)*(0.96*(delta_min_vals/W)+(0.216/0.03)*(delta_min_vals/W).^2);

delta_oth_vals = delta(~delta_min);
delta(~delta_min) = ((P+0.08*P)*W*(W*D).^0.5*(2.4*((delta_oth_vals/W)-0.03)));

% delta now represents the zdelta you were looking for

If you want to perform the same thing using non-vectorized calculations (I discourage you because Matlab has better performance when you work with vectorized calculations), for example within a for-loop, use this code:

D = 22.441;
W = 9.843;
P = 65.27;

delta = [0,0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.6, 4,4.4];
delta_size = size(delta);

zdelta = NaN(delta_size);

for i = 1:delta_size(2)
    delta_curr = delta(i);

    if (delta_curr < 0.9843)
        zdelta_curr = ((P+0.08*P)*W*(W*D)^0.5)*(0.96*(delta_curr/W)+(0.216/0.03)*(delta_curr/W)^2);
    else
        zdelta_curr = ((P+0.08*P)*W*(W*D)^0.5*(2.4*((delta_curr/W)-0.03)));
    end

    zdelta(i) = zdelta_curr;

    disp(zdelta_curr);
end

Upvotes: 3

Related Questions