使用Matlab绘制条件下的函数[重复]

问题描述 投票:-1回答:2

这个问题在这里已有答案:

我正在寻找这个问题的解决方案:

考虑函数f(x)= 2x + 1,其中x属于[0,1000]。绘制f的代表性曲线作为x的函数,因此如果|| f(x)|| <3,f的代表性曲线为红色,否则表示蓝色的f曲线。

帮帮我,因为我是Matlab软件的新用户

matlab matlab-figure
2个回答
2
投票

下面的代码应该可以解决问题:

% Obtain an array with the desired values
y = myfunc(x);

% Get a list of indices to refer to values of y 
% meeting your criteria (there are alternative ways
% to do it
indInAbs = find((abs(y)<3));
indOutAbs = find((abs(y)>=3));

% Create two arrays with y-values
% within the desired range
yInAbs = y(indInAbs);
xInAbs = x(indInAbs);

% Create two arrays with y-values
% outside the desired range
yOutAbs = y(indOutAbs);
xOutAbs = x(indOutAbs);

% Plot the values
figure(1);
hold on;
plot( xInAbs, yInAbs, 'r')
plot( xOutAbs, yOutAbs, 'b')
legend('in abs', 'out abs', 'location', 'best')

有其他方法可以做到更高效和优雅。但是,这是一个快速而肮脏的解决方案。


0
投票

您的阈值不能太低,否则没有足够的数据绘制(如果阈值= 3)或无法看到蓝色部分。在这里,我使用500,你可以看到。

function plotSeparate
    clc
    close all
    k=0
    threshold=500
    for x=1:0.5:1000
        k=k+1
        y=f(x)
        if abs(y)<threshold
            t(k,:)=[x,y];
        else
            s(k,:)=[x,y];
        end
    end
    plot(s(:,1),s(:,2),'-r',t(:,1),t(:,2),'-b')
end

function y=f(x)
    y=2*x+1;
end
© www.soinside.com 2019 - 2024. All rights reserved.