How do I include a loop while writing out a function

3 visualizaciones (últimos 30 días)
Leah Kocian
Leah Kocian el 20 de Nov. de 2015
Respondida: Tushar Athawale el 25 de Nov. de 2015
function [mean,std] = stats(x)
A = (1:1:x);
B = numel(A);
C = sum(A);
D = (C/B);
disp(mean)
end
  1 comentario
Walter Roberson
Walter Roberson el 20 de Nov. de 2015
What would the loop calculate?
By the way, it is a bad idea to use "mean" as the name of a variable, as "mean" is the name of a MATLAB routine. You are going to confuse other people and yourself when you use a variable name that is the same as the name of a common routine.

Iniciar sesión para comentar.

Respuestas (1)

Tushar Athawale
Tushar Athawale el 25 de Nov. de 2015
As suggested by Walter in one of the comments, it is probably the best to replace variable name 'mean' with a new name since MATLAB has in-built function named "mean". In your example, you can use a for loop to perform the mean computation using following code:
function [mn,std] = find_mean(x)
A = (1:1:x);
sum = 0;
num = numel(A);
for i=1:num
sum = sum + A(i);
end
mn = sum/num;
disp(mn);
end
However, it is recommended to use MATLAB in-built functions such as "sum", "mean" and so on whenever possible for efficient computations. I hope this answers your question.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by