String 从矩阵列中读取和检测字符串
矩阵中有一列字符串String 从矩阵列中读取和检测字符串,string,matlab,matrix,String,Matlab,Matrix,矩阵中有一列字符串 X = ['apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)'; 'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)' ] 我需要创建另一列矩阵来重新定义X的内容 例如,我希望MATLAB将“apple”重新定义为1,“orange”重新定义为2。因此,最终我会期待这样的事情: [1; 1; 1; 2; 2; 2] 但是,当我读取字符串列时,MATLAB无法读取字符串: theMatri
X = ['apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)'; 'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)' ]
我需要创建另一列矩阵来重新定义X的内容
例如,我希望MATLAB将“apple”重新定义为1,“orange”重新定义为2。因此,最终我会期待这样的事情:
[1; 1; 1; 2; 2; 2]
但是,当我读取字符串列时,MATLAB无法读取字符串:
theMatrix = xlsread(myFile.xls);
for i = numTotalTrials;
X = theMatrix(i,2)
> X = Nan
此外,我正在使用strfind
重新定义列:
t = strfind(X,'a');
if t == 1
newColumn = 1
else
newColumn = 2
end
MATLAB是这样工作的吗?谢谢 不知道,如果这确实是你想要的,但是从开始
X = ['apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)';
'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)'];
我将定义一个输出向量结果
,在输入上循环,只需查找
使用strfind
的所需字符串
result = zeros(size(X, 1), 1);
for row = 1 : size(X, 1)
if ~isempty(strfind(X(row,:), 'apple'))
result(row) = 1;
elseif ~isempty(strfind(X(row,:), 'orange'))
result(row) = 2;
end
end
这会回来的
result = [1; 1; 1; 2; 2; 2];
另一种使用正则表达式的解决方案:
%# note the use of cell-arrays
X = {'apple1 (15%)'; 'apple2 (15%)'; 'apple3 (15%)';
'orange1 (15%)'; 'orange2 (15%)'; 'orange3 (15%)'};
%# match either apples or oranges
m = regexp(X, '^(apple|orange)', 'match', 'once');
%# which one was found
[~,loc] = ismember(m, {'apple','orange'})
结果是:
>> loc
loc =
1
1
1
2
2
2
我已经修正了你问题的格式,但是仍然有语法错误。请再次检查代码。此外,我还不确定我是否理解您想要实现的目标,您是否只是想用数字1替换“苹果”,用2替换“橙子”?您是否尝试过使用
regexp
或regexprep
?@BenA.:+1我发布了一个使用正则表达式的解决方案:)