MATLAB: How do you store data created in a loop in a vector

vectors

The problem is calculating the speed of a car based off of the time it take for a sensor to read the front and back wheels, which in turn is based off of the distance between the 2. here's the code
%input number of cars driven over the cable
ncars=input('how many cars have driven over the sensor today, must be >2: ');
while ncars<=2 || round(ncars) ~= ncars
ncars=input('ERROR invalid number of cars, must be >2, try again : ');
end
%set up speed limit specification
speedlimit=input('\n what is the speed limit for the specified road, must be >10 : '); %mph
while speedlimit <= 10 || round(ncars) ~= ncars
speedlimit=input('\n ERROR invalid entry for speedlimit (must be >10), try again : ');
end
%generate random wheelbase between 104 and 106 inches
wheelbaseoriginal=rand(104*2);
%convert wheelbase to miles
wheelbase=(wheelbaseoriginal/12)/5280;
%initiate loop for number of cars
total=0;
carnumber=1
%initiate vector to be updated later
velocities=[ncars];
for ncars=1:1:ncars
%generate random time difference for front to back tires
tlow=wheelbase/speedlimit*1.2;
thigh=wheelbase/speedlimit*0.9;
wheeltime=tlow+thigh*rand;
%calculate the speed of each car
speed=wheeltime*3600;
velocities(carnumber)=speed;
total= speed+total;
carnumber=carnumber+1
end

Best Answer

To store data in the vector, use the variable that is being used for the loop as the vector index. data(n)=answer It's always a good idea to preallocate a vector of the expected vector size created in the loop, to run the code more efficiently.
total=0;
velocities=zeros(ncars,1);
for n=1:ncars
tlow=wheelbase/speedlimit*1.2;
thigh=wheelbase/speedlimit*0.9;
wheeltime=tlow+thigh*rand;
speed=wheeltime*3600;
velocities(n)=speed;
total=total+speed;
end
Some errors in the original code:
You were using "ncars" as the loop variable. This will overwrite the value you had the user input earlier.
For loops without an increment default to "1". ie. n=1:1:10 is the same as n=1:10. Not really an error, just an fyi.
The variable "carnumber" was redundant, the same as your loop variable (n).
Early in your code you have for the wheelbase rand(104). This will generate a 104x104 matrix of random variables. You want it to be 104+2*rand for random value between 104-106.