您可以轻松地将这些字符串转换为数字,然后将其用作索引。对于给定的字符串,b0002:
s = 'b0002'
str2num(s(2:end); % output = 2
此外,您还可以使用 char 矩阵执行此操作:
t = ['b0002';'b0003';'b0004']
t =
b0002
b0003
b0004
str2num(t(:,2:end))
ans =
2
3
4
首先,我们使用textscan将数据读取为两个字符串和一个浮点数(可以使用其他数字格式。我们必须先打开文件进行读取。
fid = fopen('myfile.txt');
A = textscan(fid,'%s%s%f');
textscan 返回一个元胞数组,因此我们必须提取您的三个变量。 x 和 y 使用 cell2mat 转换为单个字符数组(仅当其中的所有字符串长度相同时才有效),n 是数字列表。
x = cell2mat(A{1});
y = cell2mat(A{2});
n = A{3};
我们现在可以将 x 和 y 转换为数字,方法是告诉它占用每一行 :,但只占用行的倒数第二部分 2:end,例如 002, 003,而不是 b002, b003。
x = str2num(x(:,2:end));
y = str2num(y(:,2:end));
索引的小问题 - 如果我有一个矩阵 A 并且我这样做:
A = magic(8);
A([1,5],[3,8])
然后它返回四个元素 - [1,3],[5,3],[1,8],[5,8] - 而不是两个。但是您想要的是矩阵中相当于x(1),y(1) 的位置设置为n(1) 等等。为此,我们需要 1) 计算出矩阵的最终大小。 2) 使用sub2ind 计算正确的位置。
% find the size
% if you have a specified size you want the output to be use that instead
xsize = max(x);
ysize = max(y);
% initialise the output matrix - not always necessary but good practice
out = zeros(xsize,ysize);
% turn our x,y into linear indices
ind = sub2ind([xsize,ysize],x,y);
% put our numbers in our output matrix
out(ind) = n;