MATLAB: Value not multiplying by -1

if statementmultiplication

I have a nested if statement which works as it is supposed to until the last iteration.
Does anyone know why it is not multiplying the last value by -1?
w = x_0 % zero vector
k = 0 % zero value
i=1 % initial value for count
j=-1 % coefficient
for i = 1:n
if Raw_Data(i,2) == Raw_Data (i,3)
fprintf ('ERROR!!!!!)
else if Raw_Data(i,3) == val
w(i,1) = Raw_Data(i,4)
else if Raw_Data(i,2) == val
w(i,1) = j* Raw_Data(i,4)
% Rationalisation Not Working
else w(i,1)= j* Raw_Data(i,4)

Best Answer

  • I would suggest to avoid the loop and use logical indexing:
    ind = Raw_data(i,3) == val;
    w(ind) = Raw_data(:,4);
    w(~ind) = j*Raw_data(:,4);
    if any(Raw_Data(i,2) == Raw_Data (i,3))
    error('values in column 2 and 3 are identical.')
    Note that in your code
    else if Raw_Data(i,2) == val
    is not needed, because
    w(i,1) = j* Raw_Data(i,4)
    in any case.
    And if w is a vector, w(i) is the same as w(1,i).