How do I include a loop while writing out a function

1 回表示 (過去 30 日間)
Leah Kocian
Leah Kocian 2015 年 11 月 20 日
回答済み: Tushar Athawale 2015 年 11 月 25 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by