For Loop for matrix input array (without sum)

3 ビュー (過去 30 日間)
bondpen
bondpen 2018 年 8 月 28 日
編集済み: bondpen 2018 年 8 月 28 日
Hi
I trying to make a function for loop that will follow a example formula without use of sum.
Example Formula: (1/n)*sum(x+1)
where n is number of elements while x+1 is vector values.
For example if input vector is [4,6] (1/2)*(4+1)+(6+1)
I know I can use sum equation but why doesn't below work? Do I need split up x+1 into a different for loop equation? or is input i = 1:n incorrect
function Mean = mean2(vector)
[m,n] = size(vector);
for i = 1:n
Mean=(1./n)*i+1;
end

採用された回答

Stephen23
Stephen23 2018 年 8 月 28 日
編集済み: Stephen23 2018 年 8 月 28 日
"but why doesn't below work?"
Because you overwrite the results of every loop iteration with the results of the next iteration. Basically without indexing or some arithmetic you throw away the results of each loop iteration, except for the very last one. You need to do something like this:
function Z = mean2(vector)
N = numel(vector);
Z = 0;
for k = 1:N
Z = Z + vector(k)
end
Z = Z/N;
end
  1 件のコメント
bondpen
bondpen 2018 年 8 月 28 日
So you need do sum function first and then add up for loop to like (1/n)?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

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