你不能有一个既包含数值又包含字符串的数组。
如果你想同时拥有数值和字符串,你必须使用cellarray。
正如您所写,由于您不喜欢具有两个字段的结构,因此使用 textscan 似乎是一种很有前途的方法,即使它有点复杂。
你可以通过指定来克服format规范的问题:
-
format 为string
-
delimiter 为 '(在您的示例中,文本包含在两个 ' 中)
您的输入文件将作为一组字符串存储在一个单元阵列中。
现在您可以通过扫描元胞数组的元素来提取数值和字符串。
要识别数值,您可以尝试使用函数str2num 将字符串转换为数值数组:
- 如果字符串只包含数字值,您可以将这些值累积存储在一个数组中
- 如果转换失败,说明它是一个字符串,那么你可以将它累积存储在一个字符串中
您还可以设置一个标志并使用它来允许在找到字符串时在数字输出数组中插入一个值(例如NaN);这可以让您了解字符串在输入文件中的位置。
同样对于上述两种情况,您可以评估数字或字符串的部分数组的长度并将其存储在另一个数组中。
这使您可以了解特定数字或字符串在输入文件中的位置。
在下面您可以找到上述方法的可能实现。
% Open the input file
fp=fopen('mix_n_s.dat','r');
% Read the input file as a string in a cell array using "'" as a
% delimitator
% c=textscan(fp,'%s','delimiter','''');
c=textscan(fp,'%s','delimiter','''');
% Close the input file
fclose(fp);
% Extract the cell array
a=c{1};
% Initialize the output variables
% Array with the numeric values
numeric_array=[];
% String with the string in the input file
the_strings=[];
% Array with the number of numeric values and strings
the_cnt=[];
% Define the flag for enabling the isertion of NaN in the output numeric
% array in case a string is found
insert_nan=1;
% Scan the cellarray to extract the numbers and the strings
for i=1:length(a)
x=a{i}
% If the i-th element is empty (this occurs when there are at least two
% consecutive string in the input file, do nothing
if(~isempty(x))
% If the i-th element is not empty try to convert it into a numeric array
m=str2num(x);
% If the output is not empty you have read one or more than one
% numeric values
if(~isempty(m));
% Then store them into an array
numeric_array=[numeric_array m];
% The lengh of the array gives you the number of numeric values;
% store it the array
the_cnt=[the_cnt length(m)];
else
% If the conversin failed, you have read a string; store it in a
% string
the_strings=[the_strings ' ' x];
% Store the length of the string in the array; if you store it as
% a negative value, you can recognise it later on
the_cnt=[the_cnt -length(x)];
% if the flag is on, then insert NaN in the numeric array
if(insert_nan)
numeric_array=[numeric_array NaN];
end
end
end
end
numeric_array
the_strings
the_cnt
根据您提供的输入示例(我稍微修改了字符串):
1 0 23 'x' 'x' 'x' 0 0 0 1 1 10.3 54 123.45678 'x' 'x' 'x'
输出如下(插入 NaN 的标志为 on):
numeric_array =
Columns 1 through 7
1.0000 0 23.0000 NaN NaN NaN 0
Columns 8 through 14
0 0 1.0000 1.0000 10.3000 54.0000 123.4568
Columns 15 through 17
NaN NaN NaN
the_strings =
x abcd efghilm x x x
the_cnt =
3 -1 -4 -7 8 -1 -1 -1
可以解释如下:
- 查看
numeric_array 数组:在输入文件中
- 三个数值,然后是三个字符串,然后是八个数值和三个字符串
- 查看
the_cnt数组,可以理解每个字符串的长度(去掉-符号)。
希望这会有所帮助。
卡普拉'