% Frank's test code for using Matlab
% Note that the percent signs denote "comment lines"
% A powerful feature in Matlab is being able to copy lines from
% your M-file to teh command window... use this feature to verify
% what these commands do!
clear %this clears all variables from memory.
clc %clears the command window
disp('This code gives an example of some useful Matlab commands');
disp('Written by Frank Fisher, September 2005');
A = [1, 2, 3]; %creates a 1x3 array stored in variable 'A'
B = [7, 8 ,9];
C = A .* B %will give C = [7, 16, 27], multiplies corresponding elements
D = A * B' % D = 50
% note that Matlab assumes matrix operations; thus A * B will give an error
% since you cannot multiply 1 x 3 matrices together. Try it!
x = 0:.1:1; %creates as array of points between zero and 1 in increments of 0.1.
% the general form is x = start : step : stop. Try it!
y=sin(x);
plot(x,y) %standard plot. See "help plot" for additional information
test1 = A(2) * x (8) %use parentheses to access individual or groups of numbers in a variable
% how to generate random numbers
test2=rand %gives a random number between 0 and 1
test3=rand(3) %gives a 3 x 3 matrix of random numbers
test4=rand(1,3) %gives a 1 x 3 matrix of random numbers
test5=input('Please enter a number '); %user-defined input that will be stored in variable 'test5'
test6=length(x) %gives the length of an array
test7=size(test3) %gives the rows and columns of a matrix
for i = 1:10 %for loop from 1 to 10
store1(i)=rand; %generates a random number, and stores is as element 'i' in variable 'store'
end
store2=rand(1,10); %this gives the same results as the 'for' statement above
% this is a small program that will determine how many times a number is
% smaller than a critical number
counter=0; %will use this to keep track of how many times something is true; want to initialize
store3=rand(1,10);
for j=1:10
if store3(j)<0.5
counter=counter+1; %if the condition is true, increase the value of 'counter'
end
end
%here's another cool little code. what does it do?
counter1=0;
test=0;
crit_num=input('pick a "critical number" between 0 and 1 ');
while test<1
counter1=counter1 + 1; %will tell how many times through the loop
guess(counter1)=rand; %random number generated
if guess(counter1) < crit_num
test=100; %if condition holds, want to kill the loop
end
end
% note: if pick 0.001, took 809 guesses, tehn 109, then 251
% Question: can you put this loop within a loop? For instance, have Matlab run this 10
% times and keep track of how many times it took?