9:07 AM

Falling into infinity(loops and conditions)

Well this is an album by DREAM THEATER,my favourite.What I am going to discuss here is how to write loops.As you can see that matlab is quite fun and easy to use.The syntax is not much of a problem.And if you are wrong somewhere,matlab will tell the possible reasons.Te syntax is quite flexible and if you know C,C++ or the like,matlab is 'as easy as pie'.

1.Whenever you want to start a loop you need to write 'end' at the end to denote its 'end'.Same applies for conditions also.So if you want to check if x is equal to 5 then change it to 6:

if x==5
x=6;
end

so the condition is checked here.The condition ends with an 'end'.Since you are checking if it's equal or not you are using two equal(=) signs.(One equal sign(=) would mean that you are assigning the value of x already-True for C,C++ not for matlab).Matlab will show an error.lets do the above case again:

if x=5
x=6;
end  %this will show an error

and if you have more than one conditions so do it like this:

if x==5
%statement;
elseif x==6
%statement;
end

2.for loop:

the syntax is:

for var=i:j:k
%statements;
end

var stands for a variable name.
i=starting value
j=increment
k=stop value

If no value is given for j then by default it is taken to be 1.

eg., for i=1:2:10
i
end
gives the answer:

i =

     1


i =

     3


i =

     5


i =

     7


i =

     9
3.while loop:

the syntax is:
while (condition)
%statements;
end

while loop executes until the condition is false whereas for loop executes until the variable name reaches the stop value.
eg.,

while i<5
i=i+1
end

gives

i =

     2


i =

     3


i =

     4


i =

     5
PLEASE LEAVE A COMMENT :)

0 comments:

Post a Comment