Function with for loop to calculate power mean

8 ビュー (過去 30 日間)
Dobs
Dobs 2021 年 11 月 16 日
コメント済み: Dobs 2021 年 11 月 16 日
Hi,
I wrote the following code:
function [M] = powermean(x, p)
%powermean computes power mean
% Computes the power mean with exponent p of a vector x that consists of positive real numbers only.
s = 0;
n = length(x);
for i = 1:length(x)
s = (x.^p)*(1/n);
end
result = sum(s)
end
And I defined the following variables:
x = 1:5;
p = 3;
When I now call the function:
M = powermean(x, p)
The output dispalys the correct result but it also displays the following error message: "Output argument "M" (and possibly others) not assigned a value in the execution with "powermean" function."
What does it mean and how can I get rid of the error message?
Many thanks,
Dobs
  1 件のコメント
Dobs
Dobs 2021 年 11 月 16 日
And if I change results = sum(s) to M = sum(s) then the result is displayed twice.

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

採用された回答

Net Fre
Net Fre 2021 年 11 月 16 日
編集済み: Net Fre 2021 年 11 月 16 日
When you build a function, it expects you to do something with the parameters you assigned for it. In this case, the parameter 'M' is the output of the function, but you do not assign any value to that parameter during the function's execution. The reason you still see the result displayed is that you didn't use ';' at the end of the line:
result = sum(s)
So you can just see the temporary parameter result, but not the parameter M. You should also notice that after calling the function you don't have any variable named M in your workspace. The right line you should be using inside the function is:
M = sum(s)
Which will return the right answer and assign it to your variable.
  1 件のコメント
Dobs
Dobs 2021 年 11 月 16 日
Ah yes, I didn't realize that the missing ";" is the reason why the result is displayed twice! Thank you, I fixed it and now I also have the variable M in the workspace! Thank you for your help! :)

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

その他の回答 (0 件)

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by