How to make the modfunc function work ?

2 visualizzazioni (ultimi 30 giorni)
Dionysios
Dionysios il 19 Feb 2023
Risposto: Rik il 19 Feb 2023
I have problem with the modfunc function. I get this erroe message: function out = modfunc(Population, Year)
Error: Function definition are not supported in this context. Functions can only be created as local or nested functions in code files.
Also note that I am writing in live script and I wrote the modfunc function in a different live script. Additionally, the plots work, but the the line does not appear.
My code is as follows:
% Fit an exponential function to the data
function out = modfunc(Year,Population)
out = Population(1)*exp(Population(2)*Year);
% Plot the data and the fitted function on a semi-log scale
ain=[0.3 0.3];
figure
subplot(1,2,1)
plot(Population.Year,Population.Population,'o')
hold on
plot(Population,modfunc(Population,ain),'k','LineWidth',3)
subplot(1,2,2)
semilogy(Population.Year,Population.Population,'o')
hold on
semilogy(Population,modfunc(Population,ain),'k','LineWidth',3)
xlabel('Year');
ylabel('Population');
title('World Population with Exponential Fit');
legend('Data', 'Exponential Fit');

Risposte (1)

Rik
Rik il 19 Feb 2023
A function should exist in an m file. If you want to put it in a script file, it needs to have a closing end keyword, and no other code (except for other function) may exist after it. The error you posted indicates you have not met these requirements.

Community Treasure Hunt

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

Start Hunting!

Translated by