【问题标题】:matlab strange behaviour of function sum()matlab函数sum()的奇怪行为
【发布时间】:2012-12-03 02:56:24
【问题描述】:

知道为什么 Matlab 会这样吗?

>> sum([0 0 0])
Subscript indices must either be real positive integers or logicals.

>> sum([1 1 1])

ans =

     4     4     4

和这个打了2个多小时,还是搞不定。 这是我在这发生之前运行的代码。 在运行此代码之前 - 函数 sum() 工作正常。

price = 100;
vola = 0.2;
r = 0.05;
n_step = 3;
dt = 1/250;
S0 = 100;
T = 1;

s = [1 0 0 0;1 2 0 0;1 2 3 0; 1 2 3 4];
prob = 0.5;
n_path = 2^n_step; % bottle neck for binomial approach
avg_price = zeros(n_path, 2); % first column - probability, second - average price
path_matrix = zeros(n_path, n_step); % all possible paths 1-up, 0-down
for k = 0:n_path-1
    path_matrix(k+1, :) = de2bi(k,'left-msb',n_step);
end

node_matrix = path_matrix;
for k=2:n_step
    node_matrix(:, k) = node_matrix(:, k-1) + node_matrix(:, k);
end
node_matrix = node_matrix + 1;

% go through all possible paths and calculate sum of prices
for k = 1:n_path
    % probability of path
    n_up = sum(path_matrix(k, :));
    avg_price(k, 1) = prob^n_up*(1 - prob)^(n_step - n_up);

    % get sum of prices over all states for this path
    sum = s(1, 1);
    for p = 1:n_step
        sum = sum + s(p+1, node_matrix(k, p));
    end
    avg_price(k, 2) = sum;
end

【问题讨论】:

    标签: function matlab sum


    【解决方案1】:

    你已经覆盖了函数sum,现在它被认为是一个局部变量

     sum = s(1, 1);
    

    因此您隐藏 sum 作为函数。

    更改变量名并执行

     clear sum
    

    .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-19
      • 2016-01-26
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      相关资源
      最近更新 更多