Matlab错误:提示或脚本中不允许使用函数定义 [英] Matlab Error: Function definitions are not permitted at the prompt or in scripts

查看:214
本文介绍了Matlab错误:提示或脚本中不允许使用函数定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了这段代码.但这显示了错误

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

推荐答案

正如错误中指出的那样,脚本中不允许使用函数.我们看不到此脚本的启动方式,但我敢打赌它不具有 function somefunction() ...请参阅

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.

尤其是:

函数是可以接受输入参数并返回输出参数的文件[...]
函数[file]的第一行以关键字function开头.

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

您必须将函数 npvFlow 保存在单独的文件中(在Matlab路径上,称为 npvFlow.m ),或者将整个脚本放到里面函数或开头的函数.请注意,如果将脚本更改为函数,则运行后将不会在工作区中留下任何东西.

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.

您用于传递参数的语法也是无效的(请参阅Steve的注释).如果您只想固定这些参数,则不需要 npvFlow 作为函数,也可以通过使整个事物成为有效的 script 来解决此问题.>没有任何功能!

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!

这篇关于Matlab错误:提示或脚本中不允许使用函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆