在MATLAB中读取Excel文件并创建数组

时间:2014-03-10 10:05:32

标签: matlab

我有软件将坐标导出到xls文件,我现在想在MATLAB中创建一个使用这个xls文件但不希望更改原始软件的函数(因此xls文件必须保持不变格式)。

我目前正在使用代码

FILE = 'KEN FILE2.xls';
[NUM,TXT,RAW]=xlsread(FILE);
xArray = cell2mat(RAW(:,1))
yArray = cell2mat(RAW(:,2))

这不够好,因为我的excel文件如下所示:

 1     2
 2     2.1
 3     2.2  
 4     2.3


 Value of ken 
 27

由于A列中的文本代码失败,我显然可以手动编辑excel文件,以便上面的代码可以工作,但我宁愿有一个处理这个的代码。

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您可能会找到使用ismember切断单元格阵列的位置:

%//example data
a = {'1';'2';'3';'4';'';'value'};

last = find(ismember(a,''),1)-1;
a_new = a(a:last);

答案 1 :(得分:0)

代码 -

%%// Read excel file
[NUM,TXT,RAW]=xlsread(FILE);

%// Use this if you think that there might be non-empty cells on third or later 
%// columns, which you do not want to consider.
RAW = RAW(:,1:2); 

%%// Main processing starts now
RAW(cellfun(@ischar,RAW)) = {NaN};
out = cell2mat(RAW);

%%// Use this if you are okay with having NaNs to replace non-numeric data
%RAW = RAW(find(any(out,2)),:); 

%%// Use this if you want to replace all rows having any non-numeric data in them
RAW = RAW(find(all(~isnan(out),2)),:);

%// Use this if you want to stop data import at the first instance of
%// non-numeric data in any row of any column
RAW = RAW(1:find(any(isnan(out),2),1,'first')-1,:); 

%%// Output arrays
xArray = cell2mat(RAW(:,1))
yArray = cell2mat(RAW(:,2))

答案 2 :(得分:0)

假设最后两行(读作NaN27)是注释,并用2个空行分隔(raed为NaN):

[NUM,TXT,RAW]=xlsread(FILE);
[m,n]=size(NUM);
% drop off 4 last lines
xArray(:,1)=NUM(1:m-4,1);
yArray(:,1)=NUM(1:m-4,2);
%clean mess
clear NUM TXT RAW m n