有什么方法可以根据给出的变量从公式定义变量?

ber*_*bob 2 matlab

假设您有以下公式:

a=4*b*c^2
Run Code Online (Sandbox Code Playgroud)

Matlab中有什么方法可以编程,即如果提供了3个变量中的2个,Matlab将解决并提供缺失的变量?

因为我看到的唯一选择是使用开关箱并自己求解方程式。

if isempty(a)
switchVar=1
elseif isempty(b)
switchVar=2;
else
switchVar=3;
end

switch switchVar
case 1
a=4*b*c^2;
case 2
b=a/4/c^2;
case 3
c=sqrt(a/4/b);
end
Run Code Online (Sandbox Code Playgroud)

非常感谢您!

Wol*_*fie 5

对于数字(而不是符号)解决方案...

您可以通过使用一些笨拙的功能和匿名功能来做到这一点。请参阅评论以获取详细信息:

% For the target function: 0 = 4*b*c - a
% Let x = [a,b,c]

% Define the values we know about, i.e. not "c"
% You could put any values in for the known variables, and NaN for the unknown.
x0 = [5, 10, NaN];

% Define an index for the unknown, and then clear any NaNs
idx = isnan(x0);
x0(idx) = 0;

% Make sure we have 1 unknown
assert( nnz( idx ) == 1 );

% Define a function which handles which elements of "x" 
% actually influence the equation
X = @(x,ii) ( x*idx(ii) + x0(ii)*(~idx(ii)) );

% Define the function to solve, 0 = 4*b*c - a = 4*x(2)*x(3)^2 - x(1) = ...
f = @(x) 4 * X(x,2) * X(x,3).^2 - X(x,1);

% Solve using fzero. Note this requires an initial guess
x0(idx) = fzero( f, 1 );
Run Code Online (Sandbox Code Playgroud)

我们可以通过绘制函数的一系列c值来检查这些结果是否正确,并检查与x轴的交点是否与输出对齐x0(3)

c = -1:0.01:1;
y = 4*x(2)*c.^2-x(1);
figure
hold on
plot(t,y);
plot(t,y.*0,'r');
plot(x0(3),0,'ok','markersize',10,'linewidth',2)
Run Code Online (Sandbox Code Playgroud)

情节

请注意,有2个有效解,因为这是二次方。提供的初始条件fzero将在很大程度上决定找到哪种解决方案。


编辑:

您可以通过对我之前的语法进行一些调整来将此压缩为一点:

% Define all initial conditions. This includes known variable values
% i.e. a = 5, b = 10
% As well as the initial guess for unknown variable values
% i.e. c = 1 (maybe? ish?)
x0 = [5, 10, 1];
% Specify the index of the unknown variable in x
idx = 3;
% Define the helper function which handles the influence of each variable
X = @(x,ii) x*(ii==idx) + x0(ii)*(ii~=idx);
% Define the function to solve, as before
f = @(x) 4 * X(x,2) * X(x,3).^2 - X(x,1);
% Solve
x0(idx) = fzero( f, x0(idx) )
Run Code Online (Sandbox Code Playgroud)

这种方法有你可以改变的好处idx(并重新运行定义步骤Xf),以变速开关的选择!