store the data in dat file with loop function

3 views (last 30 days)
the question is : there a machine for n piece of pipe. Each pipe should measure weight and length and save as pipe.dat file. weight should keep between 4.5 to 5.1 and length should be 15.3 and 15.4. I have to count how much piece of pipe is reject there. For example, like ,if i have
4.64 15.30
5.21 15.36
4.79 15.39
first column with weight second with weight . And should be display : 'There were 1 rejects.'
weight = rand*(5.3-4.3)+4.3;
length = rand*(15.6-15.1)+15.1;
for i = 1:n
weight([n,1]);
length([n,2]);
save ('pipe.dat','-ascii', '-tabs');
load pipe.dat;
if weight >= 4.5 && weight <=5.1 && length >= 15.3 && length <=15.4
disp('good')
else
disp('There were %d rejects',n)
end
end
I try to put weight in first column and length in second and save it in pipe.dat but it fail because i guess my code for creating data is wrong.

Accepted Answer

Geoff Hayes
Geoff Hayes on 3 Nov 2014
David - first consider trying to create the data that you need. If n pieces of pipe are required then initialize your weights and lengths as
n = 4;
pipeWeight = rand(n,1)*(5.3-4.3)+4.3;
pipeLength = rand(n,1)*(15.6-15.1)+15.1;
The above will create two column vectors with weight and length data within the allowed intervals (so no data will be rejected). Note the naming of the local variables. You had named one of yours length which is the same as a built-in MATLAB function. Never name a local variable in this manner as it will just lead to bugs in the code.
To create a matrix of this data, just do
pipeData = [pipeWeight pipeLength];
To save this to file do
save('pipeData.dat','pipeData','-ascii');
To load data from this file do
load('pipeData.dat')
which will create a local variable named pipeData which is our 4x2 matrix of data.
Note that in your code, you are iterating over n (which has yet to be defined) and are saving and loading on each iteration. Just do the load outside of the for loop, and then iterate over each row of pipeData
% reject counter
numRejects = 0;
for k=1:size(pipeData,1)
% if pipe weight is invalid then increment counter
% else if pipe length is invalid then increment counter
end
disp('There were %d rejects', numRejects)
Display the number of rejects after you iterated over each pipe. Now just fill in the if and elseif (or just use a modified version of your if and else statement) accessing the kth pipe weight as
pipeData(k,1)
and the kth pipe length as
pipeData(k,2)
Since our pipe data has been generated within the desired intervals, there will be no rejects.
  2 Comments
david Chan
david Chan on 4 Nov 2014
the explanation is so detail, it helps me a lot. Thanks!

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!