How do I include a loop while writing out a function

1 Ansicht (letzte 30 Tage)
Leah Kocian
Leah Kocian am 20 Nov. 2015
Beantwortet: Tushar Athawale am 25 Nov. 2015
function [mean,std] = stats(x)
A = (1:1:x);
B = numel(A);
C = sum(A);
D = (C/B);
disp(mean)
end
  1 Kommentar
Walter Roberson
Walter Roberson am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Tushar Athawale
Tushar Athawale am 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.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by