A function that outputs the mean and standard deviation
59 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
function mean_stdev
A=rand(1,100);
% This function calculates the mean and standard deviation without
% using in-built functions
som=0;
for i=1:length(A)
som=som+A(i);
end
M=som/length(A); %the mean
moy=0;
for i=1:length(A)
moy = (A(i)-M)^2
moy = sqrt((moy)/length(A));
end
VSD=moy/length(A); %Varaince
end
i get 100 results when i run this code. My aim is to call the function then enter a series of numbers then output the standard daviation and the mean. Where am i going wrong?
0 Commenti
Risposte (2)
And_Or
il 31 Mag 2020
Hello Christopher
I think that what you want is to define a function like this:
function [M, VSD] = mean_stdev(A)
% This function calculates the mean and standard deviation without
% using in-built functions
som=0;
for i=1:length(A)
som=som+A(i);
end
M=som/length(A); %the mean
moy=0;
for i=1:length(A)
moy = (A(i)-M)^2
moy = sqrt((moy)/length(A));
end
VSD=moy/length(A); %Varaince
end
This function has an input (A) and two outputs (M, VSD). Once you have defined that function, you can call it from outside:
%Define your input values
A=rand(1,100);
%Call the function
[myMean myStdDev] = mean_stdev(A)
The function should return the mean value and the standard deviation in the outputs of the function, which I have called myMean and myStdDev.
Matlab includes some built-in functions that can be used to calculate the mean and the standard deviation of an array.
myMean = mean(A); %Mean function
myStdDev = std(A); %Standard deviation
2 Commenti
And_Or
il 31 Mag 2020
Modificato: And_Or
il 31 Mag 2020
Two things:
1-In the function I suggested, you could pass the data as an input for the function. The "input" function is not required if you pass the array as an put for the function.
[myMean, myStdDev] = mean_stdev([3,6,1,7,8,9])
2-If you want both mean and standard deviation outputs, you should call the function with two variables between brackets, as I have done. You would have the mean value stored in "myMean" and the standard deviation in "myStdDev".
the cyclist
il 31 Mag 2020
Modificato: the cyclist
il 31 Mag 2020
The reason you are displaying 100 results is that you do not have a semicolon after this line:
moy = (A(i)-M)^2
so the results are sent to the display for every iteration of the for loop.
You are calculating just the results you intend, I believe: M and VSD.
I won't correct the standard deviation result, as I assume this is a school assignment. But a hint is that you are not carrying out a sum in that calculation as you should be, and I don't think you want the square root as part of the for loop.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!