【问题标题】:"Array indices must be positive integers or logical values"“数组索引必须是正整数或逻辑值”
【发布时间】:2021-01-18 10:18:59
【问题描述】:

Problem Details and clues

%For this problem write a script file called NC.m that implements 
%the Newton-Cotes method of integration for an arbitrary function f(x). It
%should take as inputs the function and the limits of integration [a: b] and
%output the value of the definite integral. Specifically, you should use the
%Trapezoid rule as presented in Equation (11.73)
function [f]= NC(a,b,fun) %newton-cotes 
%a and b are limits of intergration 
%setting it up 
f(a)= fun(a); %y value for lower limit 
f(b)= fun(b); %y value for upper limit 
%the actual function 
f= (b-a)*(f(a)+f(b))/2; 
end 
 

我做错了什么?当我输入时, [f]= NC(-3,0,fun) 并设置 fun= @(x)normpdf(x) 。它不断返回“数组索引必须是正整数或逻辑值”。有人可以对此有所了解吗?

【问题讨论】:

    标签: matlab math integration


    【解决方案1】:

    问题是您尝试将a=0 分配给f(a),因此您在向量索引和值之间混合,以及将f 用于两个不同的目的,一个作为函数NC 的输出, 和 fun(x) 的值,这不是一个好主意。

    相反,您可以在单独的变量中定义输出:

    fa=fun(a);
    fb=fun(n); 
    f=(b-a)*(fa+fb)/2;
    

    或者直接写:f=(b-a)*(fun(a)+fun(b))/2;

    【讨论】:

      【解决方案2】:

      问题在于分配给f(a)f(b)

      f(x) 语法在 MATLAB 中有三种解释,取决于f 的类型:

      1. 使用严格的正整数索引(或逻辑索引)x 索引数组f
      2. 使用变量x 的值评估函数句柄f
      3. 使用符号变量x以某种方式操作符号函数f(x)

      由于 MATLAB 的动态类型和默认为双精度数组,MATLAB 将对 f(a)f(b) 的赋值解释为第 (1) 项:MATLAB 将 f 视为双精度数组并期望 @987654334 @ 和 b 是数组的有效索引。

      那么,根据您的意图,对不带括号的变量符号(例如,fafb)的简单赋值应该可以解决您的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 2012-04-14
        • 2016-02-16
        相关资源
        最近更新 更多