How to resolve the algorithm Averages/Mode step by step in the Octave programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Averages/Mode step by step in the Octave programming language
Table of Contents
Problem Statement
Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Averages/Mode step by step in the Octave programming language
Source code in the octave programming language
function m = mode2(v)
sv = sort(v);
% build two vectors, vals and c, so that
% c(i) holds how many times vals(i) appears
i = 1; c = []; vals = [];
while (i <= numel(v) )
tc = sum(sv==sv(i)); % it would be faster to count
% them "by hand", since sv is sorted...
c = [c, tc];
vals = [vals, sv(i)];
i += tc;
endwhile
% stack vals and c building a 2-rows matrix x
x = cat(1,vals,c);
% sort the second row (frequencies) into t (most frequent
% first) and take the "original indices" i ...
[t, i] = sort(x(2,:), "descend");
% ... so that we can use them to sort columns according
% to frequencies
nv = x(1,i);
% at last, collect into m (the result) all the values
% having the same bigger frequency
r = t(1); i = 1;
m = [];
while ( t(i) == r )
m = [m, nv(i)];
i++;
endwhile
endfunction
a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
mode2(a)
mode(a)
a = [1, 1, 2, 4, 4];
mode2(a) % returns 1 and 4
mode(a) % returns 1 only
You may also check:How to resolve the algorithm Create a file on magnetic tape step by step in the Delphi programming language
You may also check:How to resolve the algorithm System time step by step in the HolyC programming language
You may also check:How to resolve the algorithm Floyd's triangle step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Apply a callback to an array step by step in the Swift programming language
You may also check:How to resolve the algorithm Strong and weak primes step by step in the Ruby programming language