Function with for loop to calculate power mean
10 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!