0

I have written this code. But it shows the error

Function definitions are not permitted at the prompt or in scripts.

Can anyone help me out with it? what am i doing wrong?

function [npv, pvAtPeriod]= npvFlow([100 -5 100],0.04, [1 2 4])
    if isscalar(periods)      
        t = 1:4;
    else        
        t = periods;
    end
    if isscalar(payments)      
        c = zeros(1,length(t));
        c = c+payments;
    else 
        c = payments;
    end
    if numel(c)~=numel(t)
        disp('Error: Payment or period missing.')
        return
    end

    r=rate;

    pvPeriod = c./(1+r).^t;
    npv=sum(pvPeriod);

    pvAtPeriod = [t', pvPeriod'];
end
m7913d
  • 10,244
  • 7
  • 28
  • 56
  • 2
    In addition to the first answer, you have data instead of arguments. Your first line should probably be something like `function [npv, pvAtPeriod]= npvFlow(periods,payments,rate)` (I've guessed the order). If you want default arguments, see [Default Arguments in Matlab](https://stackoverflow.com/q/795823/5358968) – Steve Jul 13 '17 at 11:04

1 Answers1

1

As it states in the error, functions aren't allowed in scripts. We can't see how this script starts, but I'd wager it isn't with function somefunction()... See this documentation.

In particular:

Functions are files that can accept input arguments and return output arguments [...]
The first line of a function [file] starts with the keyword function.

You must either save your function npvFlow in a separate file (on the Matlab path, called npvFlow.m) or put the whole script inside a function or starting with a function. Note that if you change your script into a function then you won't be left with anything in your workspace after running.


Your syntax for passing arguments is invalid too (see Steve's comment). If you only ever want those arguments to be fixed, then there is no need for npvFlow to be a function and you could also resolve this issue by making the entire thing a valid script with no functions!

Wolfie
  • 27,562
  • 7
  • 28
  • 55