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

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

 Accepted 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.

5 Comments

updated the code with what was written however now it is giving me this error
In an assignment A(:) = B, the number of elements in A and B must be the same.
Error in Lab10_speedlimit (line 42) velocities(n)=(speed);
also on a sidenote the carnumber variable was for a later part in the lab when you have to display the carnumber and wheelbase etc.
Number of elements assignment is from this line:
wheelbaseoriginal=rand(104*2);
Creates a 208x208 matrix of random numbers between 0-1
It can be changed to:
wheelbaseoriginal=104+2*rand;
Creates 1 random number between 104-106
Ok fixed that and started finishing the rest of the lab including graphing the velocities and this is what I get now
Index exceeds matrix dimensions.
Error in Lab10_speedlimitv2 (line 45) fprintf('for car number %d\n, the wheelbase was %.2d\n, and the speed was %.3d\n', carnumber(n),wheelbase(n),speed(n))
here's the rest of the code
%generate random wheelbase between 104 and 106 inches
wheelbaseoriginal=104+2*rand;
%convert wheelbase to miles
wheelbase=(wheelbaseoriginal/12)/5280;
%initiate loop for number of cars
totalspeed=0;
carnumber=1;
%initiate vector to be updated later
velocities=zeros(ncars,1);
for n=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(n)=(speed);
%calculate the total speed
totalspeed= speed+totalspeed;
carnumber=carnumber+1;
fprintf('for car number %d\n the wheelbase was %.2d\n and the speed was %.3d\n', carnumber(n),wheelbase(n),speed(n))
end
%calculate average velocity
averagespeed=mean(velocities);
%define graph for speedlimit
limit=linspace(speedlimit, 100);
%plot speedlimit and scattered velocities
plot(velocities);
hold on;
plot(limit)
xlabel('car number')
ylabel('velocities(mph)')
legend('velocity of car','speedlimit')
title('velocities of cars')
%display good/bad message
if averagespeed > speedlimit
fprintf('everyones driving faster than that, you should probably bump the speed limit up')
else
fprintf('speed limit seems good, everyone driving right around there')
end
On the fprint line at the end of your loop, you're using these:
carnumber(n),wheelbase(n),speed(n)
But they're defined as:
speed=wheeltime*3600;
carnumber=carnumber+1;
wheelbase=(wheelbaseoriginal/12)/5280;
These three are defined as single value variables. Not vectors. So, in the second loop, it will try to access speed(2), aka the second value in the vector 'speed', which doesn't exist. To fix that, just remove the "(n)" from those 3.
rog. thank you sir. you have saved my ass 3 times in an hour. haha

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!