help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: plotting userdefined function


From: James Sherman Jr.
Subject: Re: plotting userdefined function
Date: Mon, 20 Nov 2017 10:57:12 -0500

On Mon, Nov 20, 2017 at 6:44 AM, Andrey <address@hidden> wrote:
Hello!

I try to plot userdefined function, but on screen only horizontal line at
50.
What is wrong with my function?

%==========================================
function ua = fnUA(x)
      if x > 0.03
        ua = 50*sin( 2*3.1415*50*x );
      else
        ua = 50;
     end;
endfunction

x=[0:0.0001:0.09];
plot(x, fnUA(x));
%=========================================

Thanks.



The function that you wrote isn't vectorized, so, when you pass your vector x to your function, when it gets to the if statement, its evaluating whether the vector x is "greater than 0.03"  which would only evaluate to true if all the values in the vector are greater than 0.03.  Here are two ways (though there are probably others) that you could get around this.
Vectorizing fnUA:
%==============
function ua = fnUA(x)
ua = zeros(size(x));
index = (x>0.3); % vector of 0's and 1's
ua(index) = 50*sin( 2*3.1415*50*x(index) ); % evaluates your function only where there is a 1 in the index vector
ua(~index) = 50; % puts 50 everywhere else
endfunction
%==============

Or use arrayfun to call your original function on each element of x:
x=[0:0.0001:0.09];
y = arrayfun(@fnUA, x);
plot(x, y);

Hope this helps,
James Sherman Jr.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]