【问题标题】:How can I plot a piecewise function in matlab whose x value depends on another function?如何在 matlab 中绘制 x 值取决于另一个函数的分段函数?
【发布时间】:2020-02-11 19:47:46
【问题描述】:

我正在尝试绘制一个依赖于 Lambda 的分段函数,但 Lambda 依赖于 m,范围从 -0.9 到 1.0。我认为我在将 H 的数据点存储在不同的 m 和 Lambda 值时遇到问题,然后告诉 matlab 根据条件语句绘制这些存储的值。这在matlab中可能吗?

我的代码如下所示

% Lambda is the lambda from Thwaites method
% where m is in the range: -0.9 < m <  1.0
m=linspace(-0.9, 1.0, 100)
Lambda = 0.45.*m/((5.*m) +1)

% H needs to be plotted as a piecewise function
% l is also a piecewise function
if (0<Lambda) && (Lambda<0.1)
    H = 2.61 -3.75*Lambda + 5.24*Lambda^2
    l = 0.22 + 1.57*Lambda -1.8*Lambda^2 
elseif (-0.1<Lambda) && (Lambda<0)
    H = 2.088 + (0.0731/(Lambda + 0.14))
    l = 0.22 + 1.402*Lambda + ((0.018*Lambda)/(Lambda+0.107))
else 
    H = 0
    l = 0
end

figure(2)
plot(m,H)
title('H vs m')
xlabel('m')
ylabel('H')

非常欢迎任何和所有的帮助!

谢谢:)

【问题讨论】:

    标签: matlab function plot piecewise


    【解决方案1】:

    只需使用掩码执行 if-else 部分。

    % Lambda is the lambda from Thwaites method
    % where m is in the range: -0.9 < m <  1.0
    m=linspace(-0.9, 1.0, 100)
    Lambda = 0.45.*m/((5.*m) +1)
    
    % allocate space for H & l (also else part in your code)
    H = zeros(1, numel(m));
    l = zeros(1, numel(m));
    
    % if condition
    cond1 = (Lambda > 0) & (Lambda < 0.1);
    % attention to the piecewise exponential operator .^, I bet you mean that
    H(cond1) = 2.61 - 3.75*Lambda(cond1) + 5.24*Lambda(cond1).^2;
    l(cond1) = 0.22 + 1.57*Lambda(cond1) - 1.8*Lambda(cond1).^2;
    
    % elseif condition
    cond2 = (Lambda > -0.1) & (Lambda < 0);
    H(cond2) = 2.088 + (0.0731 ./ (Lambda(cond2) + 0.14));  % division must be piecewise
    l(cond2) = 0.22 + 1.402*Lambda(cond2) + ((0.018*Lambda(cond2)) ./ (Lambda(cond2)+0.107));
    
    figure(2)
    plot(m,H)
    title('H vs m')
    xlabel('m')
    ylabel('H')
    

    【讨论】:

      【解决方案2】:
      % Lambda is the lambda from Thwaites method
      % where m is in the range: -0.9 < m <  1.0
      m = linspace(-0.9, 1.0, 100);
      Lambda = 0.45*m./(5*m+1);
      
      % H needs to be plotted as a piecewise function
      H = zeros(size(m));
      case1 = (0<Lambda) & (Lambda<0.1);
      H1 = 2.61 -3.75*Lambda(case1) + 5.24*Lambda(case1).^2;
      H(case1) = H1;
      
      case2 = (-0.1<Lambda) & (Lambda<0);
      H2 = 2.088 + (0.0731./(Lambda(case2) + 0.14));
      H(case2) = H2;
      
      plot(m, H);
      title('H vs m');
      xlabel('m');
      ylabel('H');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多