Function with for loop to calculate power mean

16 views (last 30 days)
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 Comment
Dobs
Dobs on 16 Nov 2021
And if I change results = sum(s) to M = sum(s) then the result is displayed twice.

Sign in to comment.

Accepted Answer

Net Fre
Net Fre on 16 Nov 2021
Edited: Net Fre on 16 Nov 2021
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 Comment
Dobs
Dobs on 16 Nov 2021
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! :)

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!