当我尝试将字符串"pi"转换为双精度时,它会被转换为NaN。
>> str2double('pi')
ans =
NaN
我正在阅读一个包含逗号分隔值的文件,其中可能包含π的倍数。例如(假设pi_in_string是从文件中读取的(:
>> pi_in_string = '0,1,-pi/6'
pi_in_string =
0,1,-pi/6
>> split_string = strsplit(pi_in_string, ',')
split_string =
'0' '1' '-pi/6'
>> str2double(split_string)
ans =
0 1 NaN
我发现我需要使用str2num而不是str2double,但str2num在单元数组上不起作用。因此,我循环遍历单元数组中的元素,首先将每个元素转换为char类型,然后使用str2num。
pi_in_string = '0,1,-pi/6';
str_array = strsplit(pi_in_string, ','); %str_array now cell array
num_elements = length(str_array); %get # elements to loop
num_vector = zeros(1,num_elements); %initialize vector
%loop through elements in str_array
for i = 1:num_elements %converting each element first to type char
num_vector(i) = str2num(char(str_array(i)));
end
使用cellfun
命令很容易避免for
循环并显式初始化num_vector
阵列:
pi_in_string = '0,1,-pi/6';
str_array = strsplit(pi_in_string, ',');
num_vector = cellfun(@(x)eval(x), str_array, 'UniformOutput', true)
num_vector =
0 1.0000 -0.5236