我有一个excel列,包含4或5个字符的字符串,我想将它们转换为数字。因此,不要“关闭”,我希望单元格包含“5”。而不是一个“打开”我想要的细胞含有“4”如何将存储在单元格数组中的字符串转换为Matlab中的数字?
[num,txt,raw] = xlsread('test.xlsx');
instructionopen = find(strcmp(raw,'open'),2);
instructionclose = find(strcmp(raw,'close'),2);
% I will try to convert a string cell to characters and the to a number.
open = []
open = []
open2 = []
for i = 1:numel(instructionopen)
open = [open; char(instructionopen(i))];
open2 = [open2; str2num(open(i))];
end
我相信我的编码是不优雅,但我basicall努力使两个数组,一个在那里我将每个字符串元素一个字符然后另一个将它们转换为数字。转换为字符后的输出给了我一个看起来像2个汉字的值(!)。我必须在那一步做点事。
我在做什么错,或者我怎么能在这些单元格中实现数字而不是字符串?
编辑
烧杯建议使用地图容器。我试过
instructions = {'open','close'};
valueSet = [1,2];
mapObj = []
for i = 1:numel(instructionopen)
if instructionopen(i) == 'open'
mapObj = containers.Map(instructions,valueSet)
end
end
但问题是mapObj出来空了,所以我一定在做smoething错误。
matlabbit建议使用字符串的长度。我试过
instructiontype = []
for h = 1:length(instructionindex)
instructiontype = [instructiontype; length(instructionindex(h))]
end
但它一直给我的数组元素的1的长度。我找不到函数strlength?
EDIT2 matlabbit建议使用cellfun(长度)
instructionindex = find(strcmp(raw,'Instruction: ')); %gets index of cells that have "Instruction" in them
instructionindex2 = char(raw{instructionindex, 2}); %converts the content of the cells one column to the right (second column) to characters
instructionindex3 = mat2cell(instructionindex2, ones(size(instructionindex2,1),1)); %converts this to a matrix of cells
instructionindex4 = cellfun('length',instructionindex2) %finally performing the conversion to the number that represents the length of the content of each cell
我现在得到的24个双打矩阵,但他们都是五元(5)......然而,有些应该是四肢(4)。
如果我没有做过mat2cell,它不会允许我执行长度函数,因为我一直收到它们不是单元格的错误。也许是因为我之前使用的字符,和我看起来像closecloseclosecloseopenopencloseopenopenopenopen ... ECT值
编辑3:张贴图片作为简化的Excel文件示例
我管理提取条件和试验的数字,但我需要为“开放”和“关闭”数字。我试图将它们转换为相应的字符串长度。
我也试过这样:
instructionindex = find(strcmp(raw(:,1),'Instruction: '));
instructionindex1 = char(raw{instructionindex,2});
instructionindex2 = mat2cell(instructionindex1, ones(size(instructionindex1,1),1));
instructionindex3 = cellfun('length',instructionindex2);
test = zeros(size(instructionindex2));
for h = 1:length(instructionindex2)
if strcmp(instructionindex2{h},'open')
test(h) = 4;
elseif strcmp(instructionindex2{h},'close')
test(h) = 5;
end
end
有趣的是这给了我数,但阵列由0的用于关闭打开和5(!)。我想现在我很好,但我真的很想知道我做错了什么!
也许你正在寻找一个[图](http://www.mathworks.com/help/matlab/ map-containers.html)容器,它可以将字符串作为键映射到数字值。 – beaker
你想要数字5还是文本表示“5”?另外,与5个字符的“close”有关吗?这真的只是一个操作? – matlabbit
感谢@beaker的建议。我编辑我的问题与我treid解决方案,但我仍然必须做错错误.. – Spica