当我只返回一个时,为什么我的函数会返回两个值?

时间:2015-02-02 15:14:37

标签: matlab matrix

所以我试图在Matlab中实现Simpson方法,这是我的代码:

function q = simpson(x,f)
n = size(x);
%subtracting the last value of the x vector with the first one
ba = x(n) - x(1);

%adding all the values of the f vector which are in even places starting from f(2)
a = 2*f(2:2:end-1);
%adding all the values of the f vector which are in odd places starting from 1
b = 4*f(1:2:end-1);

%the result is the Simpson approximation of the values given
q = ((ba)/3*n)*(f(1) + f(n) + a + b);

这是我得到的错误:

Error using ==> mtimes
Inner matrix dimensions must agree.

出于某种原因,即使我将q设为

q = f(n)

结果我得到了:

q =

 0     1

而不是

q =

 0 

当我将q设为

q = f(1)

我明白了:

q =

 0


q =

 0

我无法解释这种行为,这可能是我收到上述错误的原因。那么为什么q有两个值而不是一个?

编辑:x = linspace(0,pi/2,12); f = sin(x);

1 个答案:

答案 0 :(得分:3)

size(x)返回数组的大小。这将是具有矩阵的所有维度的向量。 必须至少有两个维度

在你的情况下,n=size(x)将给出n = [N,1],而不仅仅是数组的长度。这意味着ba将有2个元素。

您可以使用length(x)来修复此问题,numel(x)返回最长维度而不是大小(或size(x, 1)a=2*sum(f(...))或2,具体取决于x的定义方式,仅返回编号维度)

此外,您想要在a和b中求和,而现在您只需创建一个包含这些元素的向量。尝试将其更改为{{1}},类似于b。

发生错误是因为您正在对两个不同尺寸的矢量进行矩阵乘法,这是不允许的。如果您更改代码,则所有值都应为标量,以便它可以正常工作。

要得到正确的答案(3 * n)也应该在括号中,因为matlab不喜欢/和*(http://uk.mathworks.com/help/matlab/matlab_prog/operator-precedence.html)。你的版本(ba / 3)* n是错误的。

相关问题