NSCS, Week 3: Matlab Concepts
Sometimes we want to repeat a section of code until some condition is met. In the perceptual decision making model this week, we wanted the code that counted the dots to continue until the threshold was crossed. For loops can't do this because they require us to specify how many times the loop should run before hand. Instead we use while loops ... here's an example
% initialize the condition required to continue the while loop to true
% initialize a counter so we can see how many times the loop runs
% generate a random number between 0 and 1
% if the random number is bigger than 0.9 ...
% ... set the flag to false and end the while loop
In this example, we run a loop until a random number is bigger than 0.9. Every time you run it, this code will run the loop a different number of times, because the stopping condition is random.
Another way to say the same thing, without explicitly refering to the flag variable or the r variable would be
Everytime through the loop, the while line generates a new random number and checks whether it is less than 0.9. If it is, then the loop continues. If it isn't, then the loop stops.
Plotting histograms with hist
The hist function plots a histogram. For example, if we want to see what random numbers from the randn function look like we could do this ...
randn generates a random number from a Gaussian distribution with mean 0 and standard deviation 1. The histogram looks consistent with this.
With default settings, hist only uses 10 bins. If we'd like a better defined histogram we can specify the number of bins with a second argument ...
If we'd like to explicitly define the bins we can make the second argument a vector of bin edges
This gives us bin edges at whole numbers.
If we want to get the bar heights and bin centers out as variables, we can write
[barHeights, binCenters] = hist(r, 50)
Note this doesn't plot anything, but does give us numbers that we can use to plot the histogram either as a bar plot (using the bar function) or a line plot (using the plot function)