单元格内容引用非单元格数组对象

时间:2014-12-11 17:27:00

标签: matlab

使用此代码,我尝试读出一个包含3列和大量行的文本文件。我对第一栏感兴趣。我正在尝试使用cell2mat将单元转换为矩阵,但它不起作用。为什么?

错误:

  

来自非单元数组对象的单元格内容引用   cell2mat出错(第42行)
  cellclass = class(c {1});

fid=fopen('myfile123.txt');
C=textscan(fid,'%s %s %s');
C_1=str2double(C{1,1}); % first column of the cell
fclose(fid);
myCell=C_1; % 
A=cell2mat(C_1)

1 个答案:

答案 0 :(得分:2)

发生错误是因为当您尝试将其从单元格数组转换为矩阵时,C_1是双精度而不是单元格。在仅包含双精度的单元格数组上使用str2double将根据需要创建矩阵,之后无需cell2mat

此外,如果要访问单元格数组第1列的所有行,则需要使用冒号运算符,如下所示:

myCell = C_1(:) %// All the rows of the 1st column. Check the docs about referencing in cell arrays for the difference between regular braces and curly braces.

总而言之,您的代码将如下所示:

fid=fopen('myfile123.txt');
C=textscan(fid,'%s %s %s');

C_1=str2double(C(:,1)); % first column of the cell. using str2double transforms the cell array into a matrix of double, so there is no need for cell2mat afterwards.

fclose(fid);
myCell=C_1;
相关问题