[英]How to load 2D array from a text(csv) file into Octave?
考慮以下text(csv)文件:
1, Some text
2, More text
3, Text with comma, more text
如何在Octave中將數據加載到2D數組中? 該數字可以進入第一列,第一個逗號右邊的所有文本(包括其他逗號)都進入第二個文本列。
如有必要,我可以使用其他定界符替換第一個逗號。
不能將不同大小的st放入數組。 您需要創建一個所謂的單元數組 。
從問題中讀取數據的一種可能方法是將存儲在文件Test.txt中的數據讀入單元格數組中
t1 = textread("Test.txt", "%s", "delimiter", "\n");
for i = 1:length(t1)
j = findstr(t1{i}, ",")(1);
T{i,1} = t1{i}(1:j - 1);
T{i,2} = strtrim(t1{i}(j + 1:end));
end
現在
T{3,1}
為您提供3
和
T{3,2}
為您Text with comma, more text
。
經過大量的搜索和調試,這是我如何在Octave 3.2.4上運行它的方法。 使用|
作為分隔符(而不是逗號)。
數據文件現在看起來像:
1|Some text
2|More text
3|Text with comma, more text
調用方法如下: data = load_data('data/data_file.csv', NUMBER_OF_LINES);
局限性:您需要知道要獲得多少行。 如果要全部獲取,則需要編寫一個函數來計算文件中的行數,以初始化cell_array。 一切都很笨拙和原始。 對於“高級語言(如Octave)”來說,就這么多。
注意:經過使人不愉快的工作之后,看來Octave並不是很有用,除非您喜歡浪費時間編寫代碼來完成最簡單的事情。 更好的選擇似乎是帶有機器學習或矩陣庫的R,Python或C#/ Java。
function all_messages = load_data(filename, NUMBER_OF_LINES)
fid = fopen(filename, "r");
all_messages = cell (NUMBER_OF_LINES, 2 );
counter = 1;
line = fgetl(fid);
while line != -1
separator_index = index(line, '|');
all_messages {counter, 1} = substr(line, 1, separator_index - 1); % Up to the separator
all_messages {counter, 2} = substr(line, separator_index + 1, length(line) - separator_index); % After the separator
counter++;
line = fgetl(fid);
endwhile
fprintf("Processed %i lines.\n", counter -1);
fclose(fid);
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.