我如何将单元格数组转换为数组在Matlab中?
我已经从Matlab的Excel文件中读取了一些数据。 单元arrays已经生成如下:
x={'11', 'NaN', 'NaN', '13', 24}
我想将单元格数组转换为数字matrix(用于其他所需的计算),并将数字matrix中的“NaN”元素转换为零。 我该怎么做?
谢谢。
您可以使用str2double
将string转换为数字值:
x={'11', 'NaN', 'NaN', '13', '24'}; nx = str2double(x);
一旦你有数字值,你可以用零代替nan
s:
nx(isnan(nx))=0
在问题中给出的例子中有一个混合的内容(string和数字),所以需要2个步骤:
x = {'11', 'NaN', 'NaN', '13', 24}; % last value is a number isch = cellfun(@isstr,x); % find all strings numx(isch) = str2double(x(isch)); % convert the strings to numbers, and place the correcly numx(~isch) = cell2mat(x(~isch)); % extract the numbers and place the correcly
那么你可以用零replace所有的NaN
:
numx(isnan(numx)) = 0;
结果:
numx = 11 0 0 13 24