Clear Filters
Clear Filters

How do I include a loop while writing out a function

1 view (last 30 days)
function [mean,std] = stats(x)
A = (1:1:x);
B = numel(A);
C = sum(A);
D = (C/B);
disp(mean)
end
  1 Comment
Walter Roberson
Walter Roberson on 20 Nov 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.

Sign in to comment.

Answers (1)

Tushar Athawale
Tushar Athawale on 25 Nov 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.

Community Treasure Hunt

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

Start Hunting!