开发者

How do I graph the output of an equation in Matlab?

开发者 https://www.devze.com 2023-04-03 09:37 出处:网络
In Matlab, I have a function: function [ Result ] = Calc_Result(A, B, C, D) How do I graph the output of this function, for values A=0.00 to A=1.00, in steps of 0.01? Variables B,C,D are constants.

In Matlab, I have a function:

function [ Result ] = Calc_Result(A, B, C, D)

How do I graph the output of this function, for values A=0.00 to A=1.00, in steps of 0.01? Variables B,C,D are constants.

If the function returns NaN at any point on the graph, I need some method handling this (Matlab shouldn't fall ov开发者_JS百科er).


As strictlyrude27 said, if your function can deal with vectorisation, you can just use

x=0:0.01:1;
y=Calc_Result(A, B, C, D);
plot(x,y,'.-');

If not, you can use arrayfun to avoid a loop:

x=0:0.01:1;
y=arrayfun(@(A) Calc_Result(A, B, C, D),x);
plot(x,y,'.-');

plot deals with NaNs gracefully by default (it doesn't plot them and breaks the line it draws at every NaN).


fplot(@(A) Calc_Result(A, B, C, D), [0 1]);

fplot immediately plots Calc_Result on the interval [0 1]. fplot does not plot NaN values. Note that this code doesn't specify that you wanted to plot 100 points between 0 and 1 (i.e., plot at stepsizes of 0.01); fplot doesn't care about that.

If you needed that data in addition to plotting it, you could always generate it first, then plot the data afterward. If the function isn't already built to take care of matrix inputs, you could do this:

xvals = [];
yvals = [];
for A = 0:0.01:1
    y = Calc_Result(A, B, C, D);
    if ~ isnan(y)
        yvals = [yvals y];
        xvals = [xvals A];
    end
end
plot(xvals, yvals);

If it is built to deal with matrix inputs (i.e., you have a . in the right places to perform element-by-element multiplication and division), you could just do something like

A = 0:0.01:1;
y = Calc_Result(A, B, C, D);

Without knowing when it returns NaN values though, I think your best bet is to go with the for-loop. It might be a little slower than using matrix inputs, but with only 100 values to calculate I don't think it's a big deal.

0

精彩评论

暂无评论...
验证码 换一张
取 消