MATLAB: Only the last user input is being stored, the rest are being replaced by zeros in the array.

arrayuser input

Hi all, This code is meant to take user input, and store it onto a text file, however when n > 1 in my code, it will only store the last user input into the array, and replace all the previous values (of y,x,z) inputed with 0. How can this be resolved? Here is my code:
fid1 = fopen('set_p.txt','w');
prompt2 = 'How many data sets do you want to take?\n';
n = input(prompt2);
p = n-1;
clearvars x y z;
for j = 1:n
prompt3 = 'How long do you want the test to run (s)?\n';
y(n) = input(prompt3);
prompt4 = 'What sampling interval do you want to have (s)?\n';
x(n) = input(prompt4);
if p == 0
z = 0;
elseif j <= p
prompt5 = 'How long do you want between each data set (s)?\n';
z(p) = input(prompt5);
end
end
fprintf(fid1, '%6.3f,',n,y,x,z);
fclose(fid1);
Thanks for all the help in advance!

Best Answer

fid1 = fopen('set_p.txt', 'w');
% Never never never open a file without test for success:
if fid == -1, error('Cannot open file.'), end
prompt2 = 'How many data sets do you want to take?\n';
prompt3 = 'How long do you want the test to run (s)?\n';
prompt4 = 'What sampling interval do you want to have (s)?\n';
prompt5 = 'How long do you want between each data set (s)?\n';
n = input(prompt2);
p = n-1;
x = zeros(1, n); % Pre-allocate in general
y = zeros(1, n);
z = zeros(1, n);
for j = 1:n
y(j) = input(prompt3); % Not y(n), which writes the last element only
x(j) = input(prompt4);
if p == 0 %
z(j) = 0;
elseif j <= p
z(j) = input(prompt5); % Not z(p), I guess
end
end
fprintf(fid1, '%6.3f,', n, y, x, z);
fclose(fid1);