Matlab - scripts Flashcards
what does the “if” command mean when writing scripts?
if an expression is true, the next command will execute
what does the else command mean
- it often follows the if command
- if an expression is false or 0, an else command will execute the following lines of script
- must have an end
what does this line of code mean?
» A = 10;
if (A>5)
B = 1
else
B = 0
end
B = 1
if a (10) is greater than 5 then b equals 1. else if a (10) is not greater than 5, b will be 0.
what does the command for loop mean?
it will run a set of commands multiples times in a loop.
what are the rules for “for” loops
- a loop will have a counter how many times it has run through the loop
- the counter can be used within the loop as an index or a variable
- must always have an end
what is the code for a loop to run once?
i = 1
what would this code give?
for i=1:4
A(i) = i*2
end
A = 2
A = 2 4
A = 2 4 6
A = 2 4 6 8
what does this code mean?
for i=1:3
mdat(i) = mean(data(cat==i))
end
We put the counter i in the place of the number which changed between each line
and the loop will calculate the mean for each category and put the results in mdat.
Put the value you want to match in brackets after the switch statement. Each____ is a possibility, and if the value matches, then next statement will execute. It none of the cases match, the lines after _______ will execute. A____ must have an end to tell it to stop.
case
otherwise
switch
what is a switch loop?
is like testing lots of ifs one after the other. It is useful if you want to match a value to
several alternatives
Switch loops can also determine if one text string matches another text
string, and are useful for classifying text strings.
what would this code give us?
A = 3;
switch(A)
case 1
disp ‘A is one’
case 3
disp ‘A is three’
case 5
disp ‘A is five’
otherwise
disp ‘A is not one or three or five’
end
A is three
what is a while command
a while command is like a for loop which will keep going until It gets to a false value
what does this while loop code mean?
x = 1;
y = -5;
while (x==1)
y = y+1
if (y>1)
x = 2
end
end
the loop keeps increasing y until y is greater than 1. Then x is set to 2, so the loop stops.
what is a catch statement used for?
it is used for catching errors in the script and prevent them from crashing It.
example:
» A = 1:10;
» B = 1:5;
for i=1:length(A)
try
C(i) = A(i) + B(i) %% this will give an error when i
%% is greater than the length of B
catch
disp(‘B is too small’)
end
end
C = 2
C = 2 4
C = 2 4 6
C = 2 4 6 8
C = 2 4 6 8 10
B is too small