【问题标题】:Why does my Matlab function not accept an array?为什么我的 Matlab 函数不接受数组?
【发布时间】:2011-12-28 04:15:47
【问题描述】:

我有以下功能:

function [ res ] = F( n )
    t = 1.5;
    res = 0;
    if n <= 0
        return;
    end
    for i = 0:n-1
        res = res + power(-1,i)*power(t,2*i+1)/((2*i+1)*factorial(i));
    end 
end

我正在尝试将一个数组传递给它,以便我可以看到数组中每个点的输出

F([2,3,4])

由于某种原因,它拒绝对整个数组起作用,只给我第一个成员的输出。 这是为什么?

编辑:如果我改变

res = 0;

开头到

res = 0 + n;
res = res - n;

它确实适用于整个数组。

【问题讨论】:

    标签: arrays matlab parameters parameter-passing


    【解决方案1】:

    问题是 res 不是数组。你可以这样做:

    function res = F(n)
      t = 1.5;
      m = length(n);
      res = zeros(m, 1);
      for  j = 1 : m
        for i = 0 : n(j) - 1
          res(j) = res(j) + power(-1, i) * power(t, 2 * i + 1) / ((2 * i + 1) * factorial(i));
        end; 
      end;
    end;
    

    示例向量输入的结果:

    >> F([2,3,4])
    
    ans =
    
       0.375000000000000
       1.134375000000000
       0.727566964285714
    

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2015-08-21
      • 2023-03-07
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      相关资源
      最近更新 更多