2015-10-08 26 views
1

我的目標是提示用戶輸入一個值,然後在我的矩陣中輸出與他們輸入的值相對應的行。命令窗口識別我的矩陣,但不輸出特定的行,即使輸入正確的值。Matlab:我想根據用戶輸入顯示特定的矩陣行

這是我到目前爲止。

prompt='Please enter an alloy code: '; %enter either A2042,A6061 or A7005 
x=input(prompt); 
A2042=a(1, :); A6061=a(2, :); A7005=a(3, :); 
%alloy compositions a=[4.4 1.5 0.6 0 0; 0 1 0 0.6 0; 0 1.4 0 0 4.5; 1.6 2.5 0 0 5.6; 0 0.3 0 7 0]; 

所以當我輸入A2042時,我希望它顯示第1行。出於某種原因,它不合作。感謝您的幫助!

回答

1

使用switch

a=[4.4 1.5 0.6 0 0; 0 1 0 0.6 0; 0 1.4 0 0 4.5; 1.6 2.5 0 0 5.6; 0 0.3 0 7 0]; 
prompt='Please enter an alloy code: '; 
switch input(prompt) 
    case 'A2042' 
     x = a(1, :); 
    case 'A6061' 
     x = a(2, :); 
    case 'A7005' 
     x = a(3, :); 
otherwise 
    warning('Unexpected option!') 
end 
disp(x); 
-2

嘗試使用它們之前,像這樣聲明變量:

clear 

%alloy compositions 
a=[4.4 1.5 0.6 0 0; ... 
    0 1 0 0.6 0; ... 
    0 1.4 0 0 4.5; ... 
    1.6 2.5 0 0 5.6; ... 
    0 0.3 0 7 0]; 

A2042=a(1, :); 
A6061=a(2, :); 
A7005=a(3, :); 

prompt='Please enter an alloy code: '; %enter either A2042,A6061 or A7005 
x=input(prompt) 
+0

這不回答這個問題。 – excaza

+0

@excaza借調。 –

3

使用dynamic field references如果你有很多合金和不希望的選項寫出他們所有人的case聲明:

a=[4.4 1.5 0.6 0 0; 0 1 0 0.6 0; 0 1.4 0 0 4.5; 1.6 2.5 0 0 5.6; 0 0.3 0 7 0]; 

alloy.A2042 = a(1, :); 
alloy.A6061 = a(2, :); 
alloy.A7005 = a(3, :); 

prompt = 'Please enter an alloy code: '; % Enter either A2042, A6061 or A7005 
x = input(prompt, 's'); 

try 
    disp(alloy.(x)); 
catch 
    warning(sprintf('Alloy selection, %s, not found.\n', x)); 
end 
3

我會建議對每種合金的名字創建單獨的變量,即不做這行:

A2042=a(1, :); A6061=a(2, :); A7005=a(3, :); 

而是保留名稱,如一個變量:

alloyNames = {'A2042'; 
       'A6061'; 
       'A7005'; 
       ...}; %// note this must have the same number of rows as matrix a does 

現在給定的行名alloyNames匹配的正確行a

a=[4.4 1.5 0.6 0  0; 
    0  1  0  0.6 0; 
    0  1.4 0  0  4.5; 
    1.6 2.5 0  0  5.6; 
    0  0.3 0  7  0]; 

現在,當你要求輸入:

x=input(prompt) 

您可以使用strcmp找到合適的行:

idx = strcmp(alloyNames, x); 

,然後您可以顯示使用該索引正確的行:

a(idx,:) 
+0

我只是打字。做好避免動態命名的工作! – Adriaan

相關問題