MATLAB Answers

0

error in running code

Asked by Saravanan R on 19 Oct 2019 at 18:50
Latest activity Answered by Sulaymon Eshkabilov on 19 Oct 2019 at 18:57
The following code checks for majority voting algorithm.
The input is 4 floating point numbers (0.40,0.40,0.40,0.30).
The amswer is 0.40.
simple code is written and does not work.
kinldy help me.
function candidate = MajorityVote(floatno)
n = size(floatno,2);
candidate = floatno(1);
counter = 0;
for ii=1:n
if counter == 0
candidate = floatno(ii);
counter = 1;
disp(candidate);
disp(counter);
elseif candidate == floatno(ii)
counter = counter + 1;
else
counter = counter - 1;
end
end
% STEP 2: Determine if the remaining element is a valid majority element.
counter = 0;
for ii = 1:n
if floatno(ii) == candidate
counter = counter + 1;
end
end
if counter < (n+1)/2
disp('There is no Majority');
candidate = '';
end
end

  0 Comments

Sign in to comment.

1 Answer

Answer by Sulaymon Eshkabilov on 19 Oct 2019 at 18:57

It is working. It has been tested in MATLAB 2019b (it is an M-file and not a function file in this test). It also runs well if saved as a function file (under file name: MajorityVote.m) without first two lines used for testing.
A= [0.40,0.40,0.40,0.30];
candidate = MajorityVote(A)
function candidate = MajorityVote(floatno)
n = size(floatno,2);
candidate = floatno(1);
counter = 0;
for ii=1:n
if counter == 0
candidate = floatno(ii);
counter = 1;
disp(candidate);
disp(counter);
elseif candidate == floatno(ii)
counter = counter + 1;
else
counter = counter - 1;
end
end
% STEP 2: Determine if the remaining element is a valid majority element.
counter = 0;
for ii = 1:n
if floatno(ii) == candidate
counter = counter + 1;
end
end
if counter < (n+1)/2
disp('There is no Majority');
candidate = '';
end
end

  0 Comments

Sign in to comment.