PDA

查看完整版本 : 如何根据条件替换某些列值?


poster
2019-12-14, 20:13
我有一个矩阵A这样

A= 4.0000 120.0000 92.0000 0 0 37.6000 0.1910 30.0000 10.0000 168.0000 74.0000 0 0 38.0000 0.5370 34.0000 10.0000 139.0000 80.0000 0 0 27.1000 1.4410 57.0000 1.0000 139.0000 60.0000 23.0000 846.0000 30.1000 0.3980 59.0000 5.0000 136.0000 72.0000 19.0000 175.0000 25.8000 0.5870 51.0000 7.0000 121.0000 0 0 0 30.0000 0.4840 32.0000 我想做两件事:


将大于5的第一列的值替换为0。
在第二列中,如果值在121-130范围内,则将它们替换为0。如果它们在131-140范围内,则将1,替换为141-150,将2替换为151-160,以3替换。
因此,所需的结果矩阵为:

A= 4.0000 0.0000 92.0000 0 0 37.6000 0.1910 30.0000 0.0000 4.0000 74.0000 0 0 38.0000 0.5370 34.0000 0.0000 1.0000 80.0000 0 0 27.1000 1.4410 57.0000 1.0000 1.0000 60.0000 23.0000 846.0000 30.1000 0.3980 59.0000 5.0000 1.0000 72.0000 19.0000 175.0000 25.8000 0.5870 51.0000 0.0000 0.0000 0 0 0 30.0000 0.4840 32.0000 我该怎么做?

我正在尝试这样的事情:

counter=1; for i = 1: rows if A(i,1) > 5 A(i ,1) = 0; end if A(i,2) > 120 && A(i,2) < 130 A(i ,2) = 0; end counter = counter+1; end 使用案例会成功吗?



回答:

您可以像这样修改A的前2列:

A(A(:,1) > 5,1) = 0; %# Set values in column 1 greater than 5 to 0 A(:,2) = fix((A(:,2)-121)./10); %# If the values in column 2 are all 120 or %# greater you can shift, scale, then round %# them towards 0 to get the new values 上面使用矩阵索引 (http://www.mathworks.com/help/techdoc/math/f1-85462.html)和向量化操作 (http://www.mathworks.com/help/techdoc/ref/arithmeticoperators.html)来避免for循环或case语句。



更多&回答... (https://stackoverflow.com/questions/4894878)