如何将来自用户的输入存储在数组中。那么在C++中,我们必须在使用之前定义数组,或者必须为未知大小分配动态内存。但是在这个程序中,当我从数组中的用户获取输入时,它将最后输入的值存储为非全部值。我该怎么办。Matlab数组处理
for x=1:1:2
f=input('Please enter the frequency for Sinusoid Graph');
freq=[f];
end
disp(freq)
如何将来自用户的输入存储在数组中。那么在C++中,我们必须在使用之前定义数组,或者必须为未知大小分配动态内存。但是在这个程序中,当我从数组中的用户获取输入时,它将最后输入的值存储为非全部值。我该怎么办。Matlab数组处理
for x=1:1:2
f=input('Please enter the frequency for Sinusoid Graph');
freq=[f];
end
disp(freq)
编辑:
我认为tmpearce有它收入囊中,对不起,我误会了,我第一次看着它。我正在纠正我的答案,但它会像tmpearce那样看起来很多。
% preallocate array
freq = zeros(1,2);
for x=1:1:2
% prompt user for input
f=input('Please enter the frequency for Sinusoid Graph');
% make sure something got entered
if(~isempty(f))
% save the data in your array
freq(x) = f(end);
else
% alert user about the problem and quit
disp('You did not enter a frequency!');
break;
end
end
disp(freq)
%pre-allocate a 2 element vector
num_inputs = 2;
freq=nan(1,num_inputs);
%iterate from the start to the end of your freq vector
for i=1:length(freq)
f=input('Please enter the frequency for Sinusoid Graph');
if(~isempty(f))
%if a value was input, store it in freq
freq(i) = f;
end
end
通过预分配数组您使事情更加有效,你也能更轻易改变你有多少价值,要求用户输入,因为你只有在一个定义向量的长度地点。例如,您还可以添加一些输入验证,以确保数字回来。
任何其他方式。因为我不知道你写的这段代码的基础知识。其实我是初学者。 – scorpion 2012-02-27 16:22:26
@scorpion,np之间tmpearce和我更正的代码,你应该坐在漂亮。 – macduff 2012-02-27 17:01:22