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

1 回表示 (過去 30 日間)
James
James 2016 年 10 月 24 日
コメント済み: James 2016 年 10 月 24 日
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!

採用された回答

Jan
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 件)

Thorsten
Thorsten 2016 年 10 月 24 日
Move the
fprintf(fid1, '%6.3f,',n,y,x,z);
inside the for loop.

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by