2015-10-08 19 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

相关问题