Function with for loop to calculate power mean

조회 수: 2 (최근 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개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by