From help-request at octave dot org Mon Jan 24 08:58:32 2005 Subject: Re: if statement within function From: Brian Blais To: Ahn Kyung Cc: help at octave dot org Date: Mon, 24 Jan 2005 10:05:08 -0500 Ahn Kyung wrote: > I'm having trouble implementing if statement in a function. Here's an > example: > --------------------- > function y=f(x) > if (x>1) > y=1; > else > y=x.^2; > endif > endfunction > > x=[1;2]; > > > octave:3> f(x) > ans = > > 1 > 4 > > octave:4> f(1) > ans = 1 > octave:5> f(2) > ans = 1 > -------------------- > You see? f(2)=1, as expected, but if I use a vector x=[1;2];, I get > f(x)=[1;4]; When using a vector, the if statement is useless... > > I don't want to pass each element, but want to use f(x) as a chunk, with > a given vector x. What should I do to cure this problem?? > If I am understanding the issue here, you wanted f([1;2]) to return [1;1] not [1;4], right? If that is true, then you are misunderstanding the if-statement. It checks only 1 true/false value, and doesn't change the program flow for each element of the matrix. If you want the effect you state, you first need to find all of the elements of your vector x which are greater than 1, and those less than 1, and deal with it that way. For example, function y=f(x) y=zeros(size(x)); % make a return vector the same size as x idx=find(x>1); y(idx)=1; % all those elements greater than 1 are set to 1 idx=find(x<=1); y(idx)=x(idx).^2; % all those elements less than one endfunction now I get: >> x=[1;2]; >> f(x) ans = 1 1 it's a different way of thinking about the program flow, when you are dealing with vectors. I hope this helps, Brian Blais -- ----------------- bblais at bryant dot edu http://web.bryant.edu/~bblais ------------------------------------------------------------- Octave is freely available under the terms of the GNU GPL. Octave's home on the web: http://www.octave.org How to fund new projects: http://www.octave.org/funding.html Subscription information: http://www.octave.org/archive.html -------------------------------------------------------------