%% Block 1
% The double '%%' at the begining of the line indicates a new block.
% You can run just the contents of a block using 'ctrl-enter'
2+2
%% Block 2
%Here is a another block. Note you current block has yellow background.
4+4
%% Control Structures - The 'for' loop
clc % This clears the command window
% ii starts at 1 and increments at the end of the loop.
for ii=1:10
ii % This displays the current value of 'ii' each iteration of the loop
end
clc
for ii=1:.5:10 % This starts at ii=1 and increments by 0.5
fprintf('asdfasdf\n') % We can put any valid matlab code inside the loop
end
% Here is how we can add things to a variable
Cnt=0
Cnt=Cnt+5
Cnt=Cnt+5
%Sum the integers between 1 and 100 using a for loop
clc
Cnt=0 %Initialize a variable to 0
for ii=1:100
Cnt=Cnt+ii % Each time through the loop, add 'ii'
end
%% Logical Expressions
%We can ask if numbers or variables are the same, different, greater or
%less than others
1==1 %is equal? 1 for yes, 0 for no
1~=1 %is not equal? 1 for yes, 0 for no
1>2 %1 greater than 2? 1 for yes, 0 for no
1<2 %1 less than 2? 1 for yes, 0 for no
1>=2 %1 greater than or equal to 2? 1 for yes, 0 for no
1<=2 %1 less than or equal to 2? 1 for yes, 0 for no
%Note the results have the varaible type 'logical'.
%We can assign the results to a varible
Is5Equal5 = 5==5 % Note my descriptive varible name
% 'Is5Equal5' is also type 'logical'
%% Control Structures - While Loops
%The while-loop keeps running while the condition is true
clc
Cnt=0 %intialize a variable to zero
while Cnt<10 %here the condition is 'Cnt<10'
Cnt=Cnt+1 %Increment Cnt by 1 on each iteration of the loop
end
% Find how many of the lowest integers we need so that their sum is greater
% than 50
clc
N=0 % This is the integer that increases by 1 each iteration
Cnt=0 % This is the sum
while Cnt<50
N=N+1
Cnt=Cnt+N
end
% We see that we needed to add all numbers up to 10 to get over 50
%% Control Structures - 'if' - 'then'
% This is another one you will need for HW1. It is almost self-explanatory. We will look at a bit further
% on Monday, but here is the basics and a few examples. Also see 'help if'
% or 'doc if'
if 1==1 % '1==1' is the logical conditional statement
fprintf('1 equals 1!\n') %This will happen only if conditional statement is true
end
if 1==0
fprintf('1 equals 1!\n') % This won't print
end
% Let's do something inside a loop
for ii=1:10
if ii==5
fprintf('ii equals 5 on this iteration!\n')
end
end
%Trick: Select some text and hit ctrl-a. It will auto indent. Try in on
%the text below:
for ii=1:10
if ii==2
X=3;
while X<10
X=X+1
end
end
end