2013-11-24 30 views
2

我想從具有行和列標題的文本文件導入數據,並將其導入矩陣中。例如,輸入文件如下所示:如何使用行和列標題導入數據

data c1 c2 c3 c4 
r1 1 2 3 4 
r2 5 6 7 8 

此外,是否有可能與相應的數據元素訪問的行和列的名字呢?是否有可能根據操作結果對其進行修改?

在此先感謝。

回答

1

我會在格式字符串中使用textscan並額外使用%*s來吞噬每行中的第一個標題列。第一標題行應該被用來計數的列數,在情況下,它是未知的:

fid = fopen('input.txt'); %// Open the input file 

%// Read the first header row and calculate the number of columns in the file 
C = textscan(fid, '%s', 1, 'Delimiter', '\n', 'MultipleDelimsAsOne', true); 
cols = numel(regexp(C{1}{1}, '\s*\w+')); 

%// Read the rest of the rows and store the data values in a matrix 
C = textscan(fid, ['%*s', repmat('%f', 1, cols - 1)]); 
A = [C{:}];    %// Store the data in a matrix 

fclose(fid);    %// Close the input file 

的數據被存儲在矩陣A

+0

感謝您的回覆。我嘗試了它,併成功地將數據存儲在矩陣中,但是我還有另外一個疑問,如果我需要知道dataelement 3(它將是r1,c3)的列和行名稱,我將如何顯示它? – Keerthana

1

從上readtable看到http://www.mathworks.com/help/matlab/ref/readtable.html

T = readtable(filename, 'ReadVariableNames', true)如果第一列的標題

T = readtable(filename, 'ReadRowNames', true)如果第一行標題

您可能也有興趣到文檔'HeaderLines'名稱 - 值對,如果您想要放棄的不僅僅是第一行。

+0

不幸的是這個函數剛剛在Matlab 2013b中引入。 – thewaywewalk

+0

啊,我沒看到。原來的問題提到了命令,所以我認爲它有一個版本。 – athypes

+0

@athypes感謝您的迴應。因爲我正在使用2013a我不能使用可讀取選項。我的錯我清楚地提及它。 – Keerthana

1

你可以使用importdata,例如,假設分隔符是 「標籤」,

rawdata = importdata(filename, '\t'); 
row_names = rawdata.textdata(2:end,1); 
col_names = rawdata.textdata(1, 2:end); 
data_mat = rawdata.data; 

row_namescol_names單元陣列類型。如果你喜歡它們是由\t,等分隔的一個字符串,那麼你可以在它們上使用strjoin

相關問題