user3419155
user3419155

Reputation: 39

Matlab IF and ELSEIF loop

function final  = fcn(sensor1, sensor2, sensor3)

% resolution = res
res = 10;


% value1 = ((sensor1+sensor2+sensor3)/3);
% | is used for 'or' command

if
   sensor1 > res+sensor2 | sensor1> res+sensor3;
   value1 = ((sensor2+sensor3)/2);

elseif
   sensor2 > res+sensor1 | sensor2> res+sensor3;
   value1 = ((sensor1+sensor3)/2);

elseif
   sensor3 > res+sensor1 | sensor3> res+sensor2;
   value1 = ((sensor1+sensor2)/2);

else
    value1 = ((sensor1+sensor2+sensor3)/3);

end


final = value1;

I want it to display the final value based on the average. If any single value is greater than any of the other two by a certain number (resolution in this case) then it should neglect that number and just use the average of the other two. On matlab, my IF and ELSEIF loop has an error saying 'Parse error at , and Parse error at elseif.

Upvotes: 2

Views: 2267

Answers (2)

Divakar
Divakar

Reputation: 221534

You can get rid of almost all conditional statements with some vectorized approach. Additionally, it will automatically scale if you have many sensors as inputs with the same conditions.

Code

function value  = fcn(sensor1, sensor2, sensor3)

res = 10;

sensor = [sensor1;sensor2;sensor3];
ind_first_cond_met = find(any(bsxfun(@gt,sensor,(res+sensor)'),2),1,'first');

if isempty(ind_first_cond_met)
    value = mean(sensor);
else    
    sum_mat = bsxfun(@plus,sensor,sensor');
    mean_every_other_two = [sum_mat(1,2) sum_mat(2,3) sum_mat(3,1)]./2;
    value = mean_every_other_two(ind_first_cond_met);
end

Upvotes: 0

Dan
Dan

Reputation: 45752

You should have you if and your conditions on the same line. And no semi colon after the conditions:

.
.
.
if sensor1 > res+sensor2 || sensor1> res+sensor3
   value1 = ((sensor2+sensor3)/2);

elseif sensor2 > res+sensor1 || sensor2> res+sensor3
   value1 = ((sensor1+sensor3)/2);
.
.
.

btw you should be using || in this case because you're dealing with scalars.

Upvotes: 2

Related Questions