多次求解一个方程

Solve One Equation Multiple times

我有 50 个观察值作为具有变量值的行和列。对于每个观察,我使用 fsolve 来求解未知变量 q_iz。我正在尝试使用循环。我已经解决了 1st 行,但是 MATLAB 在转到 2nd 行时抛出错误。另外,我想将 k 的求解值存储在 (50,1) 维度中。

我将提供一个更简单的代码来表示问题,如下所示:

 global price gnw dataq_izc(c) c

price = ones(50,2);
gnw = ones(50,2,2);
dataq_izc = 0.20*ones(50,1);

k0 = 0.1+ zeros(50,1);
for c = 1:50
options=optimset('Display','notify','MaxFunEvals',10^7,'TolX',1e-8,'TolFun',1e-6,'MaxIter',10^5);
% Solve 
k = fzero(@qiz,k0(c,1),options);
fprintf('Quantity\n');
disp(k);
end;

脚本 'qiz' 是:

function F = qiz(k)

global price gnw dataq_izc(c) c

q_iz = zeros(50,2,2);
i = 1.;
while i < 3
    z = 1.;
    while z < 3
    q_iz(c,i,z) = k(c,1)*price(c,z)/gnw(c,i,z);
    z = z + 1.;
    end
i = i + 1.;
end;

q_izc = zeros(50);
c = 1.;
while c < 51;
i = 1.;
while i < 3
    z = 1.;
    while z < 3
    q_izc(c) = q_izc(c)  + q_iz(c,i,z);
    z = z + 1.;
    end
i = i + 1.;
end;
c = c + 1.;
end

F = q_izc(c) - dataq_izc(c,1);

当我 运行 这段代码时,它在第一行已解决,但在进入第二行时会抛出错误:

FZERO cannot continue because user supplied function_handle ==> qiz failed with the error below. Attempted to access k(2,1); index out of bounds because numel(k)=1.

您已将标量 k0(c,1) 传递给您的函数 qiz。在该函数中,您尝试访问 k(c,1) 并得到错误说明 as much.

FZERO cannot continue because user supplied function_handle ==> qiz failed with the error below. Attempted to access k(2,1); index out of bounds because numel(k)=1.

错误告诉您 knumel(k)=1 的标量。这是第一个错误。第二个是在函数 qiz 中,您正在重新分配 c 的值。您将 c 定义为 global,然后将其用作第二个循环中的索引。当 qiz 结束时,c 的值现在是 51。这超出了 k0 向量的范围。尝试始终使用有意义的变量名称来避免此错误。

这是一个有效(无错误)的版本。

function k = Test(  )

global c price gnw dataq_izc

price = ones(50,2);
gnw = ones(50,2,2);
dataq_izc = 0.20*ones(50,1);

k0 = 0.1+ zeros(50,1);
k = size(k0);
for c = 1:50
options=optimset('Display','notify','MaxFunEvals',10^7,'TolX',1e-8,'TolFun',1e-6,'MaxIter',10^5);
% Solve 
k(c) = fzero(@qiz,k0(c),options);
fprintf('Quantity: %f\n', k(c));
end

end


function F = qiz(k)

global c price gnw dataq_izc

q_iz = zeros(50,2,2);
i = 1.;
while i < 3
    z = 1.;
    while z < 3
        q_iz(c,i,z) = k*price(c,z)/gnw(c,i,z);
        z = z + 1.;
    end
    i = i + 1.;
end;

q_izc = zeros(50);
c2 = 1.;
while c2 < 51;
    i = 1.;
    while i < 3
        z = 1.;
        while z < 3
            q_izc(c2) = q_izc(c2) + q_iz(c2,i,z);
            z = z + 1.;
        end
        i = i + 1.;
    end;
    c2 = c2 + 1.;
end

F = q_izc(c) - dataq_izc(c,1);

end