2012-02-27 95 views
0

如何將來自用戶的輸入存儲在數組中。那麼在C++中,我們必須在使用之前定義數組,或者必須爲未知大小分配動態內存。但是在這個程序中,當我從數組中的用戶獲取輸入時,它將最後輸入的值存儲爲非全部值。我該怎麼辦。Matlab數組處理

for x=1:1:2 
f=input('Please enter the frequency for Sinusoid Graph'); 
freq=[f]; 
end 
disp(freq) 

回答

0

編輯:

我認爲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) 
+0

任何其他方式。因爲我不知道你寫的這段代碼的基礎知識。其實我是初學者。 – scorpion 2012-02-27 16:22:26

+0

@scorpion,np之間tmpearce和我更正的代碼,你應該坐在漂亮。 – macduff 2012-02-27 17:01:22

1

在每個迴轉循環執行語句:

freq = [f]; 

其設定freq是包含值f陣列。相反,請嘗試freq = [freq f];並注意,如果freq變大,這可能不是非常有效。

+0

所以有什麼方法可以象我們在C/C++ – scorpion 2012-02-27 16:25:05

+0

中那樣聲明數組,你可以用'freq = nan(1,10);'等多種方法預先分配數組來創建1×10的數組。跟蹤每次通過循環插入的元素(如果'i'是您的索引,請使用'freq(i)= f;' – tmpearce 2012-02-27 16:29:17

1
%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 

通過預分配數組您使事情更加有效,你也能更輕易改變你有多少價值,要求用戶輸入,因爲你只有在一個定義向量的長度地點。例如,您還可以添加一些輸入驗證,以確保數字回來。