liluziturd
liluziturd

Reputation: 1

matlab: how to fix my function that has to return the mean/mode/median of a vector

I was given a problem to find the mean, mode, and median of a single vector input in matlab. My function saves these datapoints as 3 separate variables, but I get an error each time. Any tips on how to correct this?

function mean_mode_median(v) 

  v_mean = mean(v);
  v_mode = mode(v);
  v_median = median(v);
  
  disp(v_mean);
  disp(v_mode);
  disp(v_median);
  
  end

function call:

datapoints = [ 11 22 33 44 33 12 32 14 33 14];


disp(mean_mode_median(datapoints));

The error is not enough input arguments and too many output arguments.

Upvotes: 0

Views: 222

Answers (1)

Lucien Xhh
Lucien Xhh

Reputation: 317

Description: disp(X) displays the value of variable X without printing the variable name. More details please refer to https://www.mathworks.com/help/matlab/ref/disp.html

Nomally, the X is a Matrix of numbers or strings.

In your case, mean_mode_median(v) has no return value, it means disp() will accept nothing. So the error meassage is "not enough input arguments and too many output arguments".

Two solutions:

1.Keep your function, and use mean_mode_median(datapoints) to display 3 separate variables.

2.Change your function to a more practical one, use [v_mean, v_mode, v_median] = mean_mode_median(datapoints) to receive variables and then display them.

function [v_mean, v_mode, v_median] = mean_mode_median(v) 
v_mean = mean(v);
v_mode = mode(v);
v_median = median(v);
end

Upvotes: 3

Related Questions