2010-06-20 28 views
0

如何使用FIND功能與IF聲明這個問題是關係到How can I merge this data in MATLAB?MATLAB如何使用查找功能與IF語句

?例如如果我有這樣的數據:

20 10 1 
20 11 1 
20 15 1 
23 10 1 
23 10 1 
23 12 0 

規則1: 第3列的數據必須是1

規則2: 如果n是塔1的當前索引,如果n等於n-1(20 = 20),索引n的列2的數據和n-1 被合併。

20 21 0 
20 15 0 
20 0 0 
23 20 0 
23 0 0 
23 12 0 

編輯:

fid=fopen('data.txt'); 
A=textscan(fid,'%f%f%f'); 
fclose(fid); 
in = cell2mat(A)'; %'# fix for SO formatting - Jonas 

%# rows2mergeFrom are the rows where the second row equals the first row of col 1 
%# and where the third column is 1. rows2mergeInto indicates the rows from which the 
%# values of the following rows should be added 
rows2mergeFrom = find(in(2:end,1) == in(1:end-1,1) & in(2:end,3) == 1) + 1; 

out = in; 
out(rows2mergeFrom-1,2) = out(rows2mergeFrom-1,2) + out(rows2mergeFrom,2); 

%# data that has been shifted up gets subtracted from the 'rows2mergeFrom'-rows 
out(rows2mergeFrom,2) = out(rows2mergeFrom,2) - in(rows2mergeFrom,2); 

%# remove the ones in the third column from any row that has been involved in a 
%# merge operation 
out([rows2mergeFrom;rows2mergeFrom-1],3) = 0 

fid = fopen('newData.txt','wt'); 
format short g; 
fprintf(fid,'%g\t %g\t %g\n',out); %'# Write the data to the file 
fclose(fid); 
+0

結果與您所描述的不一致! – Amro 2010-06-20 19:19:25

+0

我認爲數組應該是26,而不是25,在位置'(2,2)' – Jonas 2010-06-20 19:48:02

+0

我已經改變了輸出 – Jessy 2010-06-20 20:03:58

回答

0

沒有必要的if語句。你需要的是一個邏輯數組,允許find提取要合併的行的行索引。

更新至於我可以告訴新規則

in = [20 10 1 
20 11 1 
20 15 1 
23 10 1 
23 10 1 
23 12 0]; 

%# rows2mergeFrom are the rows where the second row equals the first row of col 1 
%# and where the third column is 1. rows2mergeInto indicates the rows from which the 
%# values of the following rows should be added 
rows2mergeFrom = find(in(2:end,1) == in(1:end-1,1) & in(2:end,3) == 1) + 1; 

out = in; 
out(rows2mergeFrom-1,2) = out(rows2mergeFrom-1,2) + out(rows2mergeFrom,2); 

%# data that has been shifted up gets subtracted from the 'rows2mergeFrom'-rows 
out(rows2mergeFrom,2) = out(rows2mergeFrom,2) - in(rows2mergeFrom,2); 

%# remove the ones in the third column from any row that has been involved in a 
%# merge operation 
out([rows2mergeFrom;rows2mergeFrom-1],3) = 0 

out = 
20 21  0 
20 15  0 
20  0  0 
23 20  0 
23  0  0 
23 12  0 
0

符合,你不需要使用查找或如果。你只需要邏輯索引。

如果我正確理解您的問題,Amro正確地指出您的輸出與您的邏輯描述不符。請嘗試以下腳本:

m = [20 10 0; ... 
    20 11 0; ... 
    20 15 1; ... 
    23 10 1; ... 
    23 10 1]; 
merge = (m(1:end-1, 1) == m(2:end, 1)) & (m(2:end,3) == 1) 
mnew = m(2:end, :); 
madd = m(1:end-1,2) + m(2:end,2); 
mnew(merge, 2) = madd(merge); 
mnew = [m(1,:); mnew]