开发者

What is wrong with my function in Octave?

I just tried to create my first function in octave, it looks as follows:

function hui(x)
if(0 <= x && x <2)
    retval = (1.5 * x + 2)
elseif(2<= x && x <4)
    retval = (-x + 5)
elseif(4<= x && x < 6)
    retval = (0.5 * x)
elseif(6<= x && x < 8)
    retval = (x - 3)
elseif(8<开发者_如何学编程= x && x <=10)
    retval = (2 * x - 11)
endif
endfunction

but if I try to plot it using: x=0:0.1:10; plot(x, hui(x));

It shows a plot witch seems a little bit strange.

What is wrong with my function in Octave?

What did I wrong?

Thanks in advance John


You'll have to pardon my rustiness with the package, but you need to change the code around a bit. Notably, the notation 0<=x is incorrect, and must be x>=0. Since hui is operating on a vector, I believe you need to take that into account when constructing your return value.

I'm sure there are more effective ways of vectorizing this, but basically, While stepping over the input vector, I added the latest value onto the return vector, and at the end lopping off the initial 0 that I had put in. I put in a sentinel value in case the input didn't fulfill one of the criteria (it was always taking the "else" path in your code, so putting something there could have alerted you to something being wrong).

function [retval] = hui(x)
retval = 0
for i=1:size(x,2)
    if(x(i)>=0 && x(i) <2)
         retval = [retval (1.5 * x(i) + 2)];

    elseif( x(i)>=2 && x(i) <4)
         retval = [retval (-1*x(i) + 5)];

    elseif(x(i)>=4 && x(i) < 6)
         retval = [retval (0.5 * x(i))];

    elseif(x(i)>=6 && x(i) < 8)
         retval = [retval (x(i) - 3)];

    elseif(x(i)>=8 && x(i) <=10)
         retval = [retval (2 * x(i) - 11)];

    else
         retval = -999;

    endif

endfor 
    retval = retval(2:size(retval,2));
endfunction


x is a vector, so you either need to loop through it or vectorise your code to removing the need.

As you're using Octave, it's worth vectorising everything you possibly can. The easiest way I can think of doing this is:

x = 0:0.1:10;
y = x;
y(x >= 0 & x < 2)  = x(x >= 0 & x < 2) * 1.5 + 2;
y(x >= 2 & x < 4)  = x(x >= 2 & x < 4) * -1 + 5;
y(x >= 4 & x < 6)  = x(x >= 4 & x < 6) * 0.5;
y(x >= 6 & x < 8)  = x(x >= 6 & x < 8) - 3;
y(x >= 8 & x < 10) = x(x >= 8 & x < 10) * 2 - 11;

The y(x >= a & x < b) syntax is logical indexing. Alone, x >= a & x < b gives you a vector of logical values, but combined with another vector you get the values which meet the condition. Octave will also let you do assignments like this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜