Matlab:我想根据用户输入显示特定的矩阵行

时间:2015-10-08 12:09:55

标签: 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行。出于某种原因,它没有合作。谢谢你的帮助!

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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,:)

答案 2 :(得分: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);

答案 3 :(得分:-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)
相关问题