Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
 
 
主题工具 显示模式
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 MATLAB如何在IF语句中使用FIND函数

这个问题与我如何在MATLAB中合并这些数据有关?

如何在IF语句中使用FIND函数?例如,如果我有此数据:

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列的n-1 (20 = 20),则将索引n和n-1的第2列的数据合并。

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);

回答:

无需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

更多&回答...
poster 当前离线   回复时引用此帖
 


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 07:37


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.