Only the last user input is being stored, the rest are being replaced by zeros in my array.
1 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
Jan
2016-10-24
编辑:Jan
2016-10-24
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);
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!