How do I include a loop while writing out a function

1 次查看(过去 30 天)
function [mean,std] = stats(x)
A = (1:1:x);
B = numel(A);
C = sum(A);
D = (C/B);
disp(mean)
end
  1 个评论
Walter Roberson
Walter Roberson 2015-11-20
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.

请先登录,再进行评论。

回答(1 个)

Tushar Athawale
Tushar Athawale 2015-11-25
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by