Info

此问题已关闭。 请重新打开它进行编辑或回答。

error in running code

1 次查看(过去 30 天)
Saravanan R
Saravanan R 2019-10-19
关闭: MATLAB Answer Bot 2021-8-20
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

回答(1 个)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019-10-19
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

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by