2017-09-06 37 views
0

我有这样的阵列:如何从阵列,其中的字符串包含在范围号码中选择行:MATLAB

AB01 4 7 
AB02 3 4 
AB02 2 4 
AB03 9 5 
AB01 3 3 
AB04 3 2 
AB05 4 1 
AB03 4 1 
AB05 3 4 
AB04 1 5 

我有确定最小值和最大值数2个输入。例如,如果我设置的第一输入n1 = 2和第二输入n2 = 4,这意味着我想这有AB02AB03或第一列AB04值的行,我会得到这样的输出:

AB02 3 4 
AB02 2 4 
AB03 9 5 
AB04 3 2 
AB03 4 1 
AB04 1 5 

我不知道如何从AB02 - AB04创建范围值,因为它不是数字。我真的很赞赏你的帮助。


编辑:我想使用这个脚本,我知道我的逻辑索引是不正确的,但我卡住了。

col1 = 3; 
fmt = repmat('%s',1,col1); 
enter cofid = fopen('Document2.txt', 'rt');de here 
filecolumn = textscan(fid, fmt, 'Delimiter', ' '); 
fclose(fid); 
FF = horzcat(filecolumn{:}); 

y1 = input('INPUT1: ') 
y = sprintf('AB%.2d',y1) 
z1 = input('INPUT2: ') 
z = sprintf('AB%.2d',z1) 
for o = y:z 
    while o == 1 
     index = find(strcmp(FF,o)) 
    end 
    ff = FF(index,:) 
end 
+1

这个问题可以被分为不同的子问题: (1)从一个字符串 (2)的范围在数组中的元素的检查提取的数 (3)逻辑索引 – m7913d

回答

1

让我们从你的单元阵列中的字符串末尾抽取的号码,你可以使用正则表达式来让事情一般,但我会假设你总是有一个2位数末一个4位数字的字符串,就像你出...

% Your data 
M = {'AB01' 4 7 
    'AB02' 3 4 
    'AB02' 2 4 
    'AB03' 9 5 
    'AB01' 3 3 
    'AB04' 3 2 
    'AB05' 4 1 
    'AB03' 4 1 
    'AB05' 3 4 
    'AB04' 1 5}; 
% Extracting numbers, using cellfun to operate on each element of the cell array 
nums = cellfun(@(r)str2num(r(3:4)), M(:,1)); 
>> nums = [1 
      2 
      2 
      % ... others ... 
      4] 

现在我们可以使用逻辑索引来访问你想要

n1 = 2; % lower bound 
n2 = 4; % upper bound 
% Create logical array, true where nums is in range [n1,n2], false otherwise  
idx = nums >= n1 & nums <= n2; 

行和检索M

output = M(idx,:); 
>> output = 
    {'AB02' 3 4 
    'AB02' 2 4 
    'AB03' 9 5 
    'AB04' 3 2 
    'AB03' 4 1 
    'AB04' 1 5} 

仅供参考,所有的代码都在一起,没有输出可能是这个样子:

% Input values 
n1 = 2; n2 = 4; 
% Your data stored in cell array M, get numbers 
nums = cellfun(@(r)str2num(r(3:4)), M(:,1)); 
% Get rows within range 
output = M(nums >= n1 & nums <= n2, :); 
+0

'str2num'使用' eval'。使用'str2double'代替 –

+0

事件更好的是使用字符串并调用double。 x =一个(1000); str = string(x); cll = cellstr(str);抽动;双(STR); TOC;抽动; str2double(CLL); toc 已用时间为0.534203秒。 已用时间为16.009992秒。 – matlabbit

+0

@matlabbit我没有2016b +(用于'string')来测试这个,但在调用数字字符串的'double'之前,它会返回一个ASCII值的数组......因此,这个建议似乎是iffy – Wolfie

0

我会建议你使用,而不是一个单元阵列中的表并使用tableread与TextType字符串来导入数据。使用字符串(从16b开始可用)提取值更简单一些。如果您处理大量数据,字符串也更快。

lower_bound = 2; 
upper_bound = 4; 

data = {'AB02' 3 4 
     'AB02' 2 4 
     'AB03' 9 5 
     'AB04' 3 2 
     'AB03' 4 1 
     'AB04' 1 5}; 

data = cell2table(data,'VariableNames',{'x','y','z'}); 
data.x = string(data.x); 

value = extractAfter(data.x,2); 
value = double(value); 

data = data(value >= lower_bound & value <= upper_bound,:) 

data = 

    6×3 table 

     x  y z 
    ______ _ _ 

    "AB02" 3 4 
    "AB02" 2 4 
    "AB03" 9 5 
    "AB04" 3 2 
    "AB03" 4 1 
    "AB04" 1 5 
相关问题