函数sum()的matlab奇怪行为 [英] matlab strange behaviour of function sum()

查看:160
本文介绍了函数sum()的matlab奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法为什么Matlab可以表现得如此?

 >> sum([0 0 0])
下标索引必须是实数正整数或逻辑。

>> sum([1 1 1])$ ​​b
$ b 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];
概率= 0.5;
n_path = 2 ^ n_step;二项式方法的瓶颈%b $ b avg_price = zeros(n_path,2); %第一列 - 概率,第二 - 平均价格
path_matrix =零(n_path,n_step); %所有可能的路径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;对于k = 2,
:n_step
node_matrix(:, k)= node_matrix(:, k-1)+ node_matrix(:, k);
end
node_matrix = node_matrix + 1;

%遍历所有可能的路径并计算k = 1时的价格总和
:n_path
%路径概率
n_up = sum(path_matrix(k, ));
avg_price(k,1)= prob ^ n_up *(1-prob)^(n_step-n_up);

%获得此路径上所有州的价格总和
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


解决方案

sum 现在它被认为是一个局部变量

  sum = s( 1,1); 

因此您是隐藏 sum 作为函数。

更改变量名称并执行

 明确总和


Any idea why Matlab could behave like this?

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

>> sum([1 1 1])

ans =

     4     4     4

Fighting with this more than 2 hours, still can't get it. This is the code I run before this happens. Before running this code - the function sum() works fine.

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

解决方案

you've overridden the function sum and now it is considered a local variable

 sum = s(1, 1);

thus you are hiding sum as function.

Change the variable name and do

 clear sum

.

这篇关于函数sum()的matlab奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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