06.07.2013 Views

Scilab Bag Of Tricks - Claymore

Scilab Bag Of Tricks - Claymore

Scilab Bag Of Tricks - Claymore

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[y, dy] = fun(x);<br />

end;<br />

x<br />

Chapter 3. Style<br />

Assuming that the function fun, and the start guess x0 are supplied by the user, we do not know how<br />

many loops it will take for Newton’s algorithm to converge, if it does converge at all. (In the example<br />

it does.) Here, the while-loop expresses this lack of a-priori knowledge.<br />

3.4.2. if/select<br />

The relationship between if and select bears similarity to while and for, respectively. In a<br />

select clause the different cases are known – and spelled out explicitely – before the thread of<br />

control enters the construct. There is a one to one relationship between the states of the selecting<br />

expression and the case branch taken. The else branch in a select works exactly as the else in<br />

an if.<br />

function f = fibonacci(n)<br />

// return n-th Fibonacci number<br />

select n<br />

case 0 then<br />

f = 1<br />

case 1 then<br />

f = 1<br />

else<br />

f = fibonacci(n - 1) + fibonacci(n - 2)<br />

end<br />

The selecting expression is not restricted to scalars, vectors for example work too:<br />

function s = shape4(m)<br />

// classify a 2x2 matrix according to its shape<br />

select abs(m)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!