A suggestion on how to handle this situation

Posted by Boteon@reddit | learnprogramming | View on Reddit | 3 comments

Imagine a situation in which a function (fun1) you have written a function that does something specific.

Now, you need another function (fun2) in which the code of fun1 is almost perfect, except for the output type. The main problem is that the output is created within a for loop (see below), thus I cannot create a sub-function that can be called from both fun1 and fun2.

Here is my question: how should I handle this? stick with copying fun1 and editing the output for fun2 or are there any other strategies?

If it helps, this is Matlab

ncut = 0;
for kk = 1:length(seq)
     if kk == 1 % Esx
        w = wEsx;
    elseif kk == length(seq) % Edx
        w = wEdx;
    else % I
        w = wI;
    end
    if all(w~=seq(kk))
        ncut = ncut+1;  %%% THIS IS THE OUTPUT OF fun1 WHICH MUST BE CHANGED FOR fun2
    end
end