Function with for loop to calculate power mean
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
Risposta accettata
Net Fre
il 16 Nov 2021
Modificato: Net Fre
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!