2016-08-18 123 views
0

我有這個原始(字符串)數據。我想先將它改爲數字,然後通過刪除斜槓將第三列分成兩部分,這樣我的最終答案將是一個四(4)列矩陣。從矩陣中提取數據

[-0.095] [ 3.251] '0.152/0.0415' 
[ NaN] [ NaN] [   NaN] 
[ 3.194] [ 3.194] [   NaN] 
[ 3.251] [ 9.911] '0.152/0.0387' 
[ NaN] [ NaN] [   NaN] 
[ 9.854] [ 9.854] [   NaN] 
[ 9.911] [16.571] '0.152/0.0387' 
[ NaN] [ NaN] [   NaN] 
[16.514] [16.514] [   NaN] 
[16.571] [23.211] '0.129/0.0535' 
[23.154] [23.154] [   NaN] 
[23.211] [29.851] '0.129/0.0535' 
[29.794] [29.794] [   NaN] 
+1

你看着'strsplit'? https://uk.mathworks.com/help/matlab/ref/strsplit.html – GameOfThrows

+0

您的示例數據是字符串中的方括號,還是它們表示分隔單元格中的字符串? – Tar

回答

0

假設輸入數據在Input.txt文件中。
輸出矩陣爲A.
該代碼讀取從文件到字符串的行,並使用sscanf將字符串解析爲向量。
每個解析的向量附加到矩陣A的底部。
當字符串沒有除法(其中最後一個元素是NaN)時的特殊情況的代碼測試。

檢查以下內容:

f = fopen('Input.txt', 'r'); 

A = []; 

while ~feof(f) 
    s = fgets(f); %Read row from file. 

    if isempty(strfind(s, '/')) 
     Q = [sscanf(s, '[%f] [%f]'); NaN; NaN]; %First case: last element is NaN: [ 3.194] [ 3.194] [   NaN] 
    else 
     Q = sscanf(s, '[%f] [%f] ''%f/%f'''); %Second case: last element is x/y: [ 3.251] [ 9.911] '0.152/0.0387' 
    end 

    %Concatenate vector Q to the bottom of A matrix; 
    A = [A; Q'];  
end 

fclose(f);