Matlab中的范围选择 [英] Range Selection in Matlab

查看:288
本文介绍了Matlab中的范围选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个6到6的矩阵,并希望在某些范围内更改值.

I defined a matrix 6 by 6 and want to make a change in values in some ranges.

c = floor(rand(6,6) * 100)

结果:

22    26    10     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25    73    81    16    69    53
29    34    26    17    69    65
61    58    59    42    63    40

然后我跑步:

c(c(1:3,:)<17) = 0

22     0     0     2     9     3
38    82    90    42    59     6
58    98    87    31    47    31
25     0     0    16    69    53
29    34     0    17    69    65
61    58    59    42    63    40

我想在1到3之间的行中将小于17的元素设为零,但是结果对我来说似乎是错误的!有什么主意吗?

I want to make elements in rows between 1 and 3 which are less than 17 zero, but the result seems wrong to me! any idea?

推荐答案

这不起作用,因为您正在根据自己的条件获取线性索引,并且子矩阵的大小与原始矩阵的大小不同. 您可以先获取下标,然后更改原始矩阵:

This does not work because you are getting linear indices from your condition and the size of the submatrix is different from that of the original one. You can first get the subscripts and then change your original matrix:

c = floor(rand(6,6) * 100)
c =

28    60    24    48    20    99
 0    78    34    80    38    70
49    11    54    37    66     8
98    57     6    51    75     4
73    87    41     9    17    49
31    68    23    90    51    44

[a,b]=find(c(1:3,:)<17);
c(sub2ind(size(c),a,b))=0
c =

28    60    24    48    20    99
 0    78    34    80    38    70
49     0    54    37    66     0
98    57     6    51    75     4
73    87    41     9    17    49
31    68    23    90    51    44

请注意,如果您不是从第一行或第一列开始,则应考虑区别:

please note that if you dont start from the first row or the first column, you should consider the difference:

[a,b]=find(c(3:6,2:5)<17);
c(sub2ind(size(c),a+2,b+1))=0

另一种解决方案是创建用于替换的索引掩码矩阵.在通常不是从第一行或第一列开始的情况下,这也将起作用:

Another solution is to create a mask matrix of indicies to use for the substitution. This would also work in the general case of not starting from the first row or column:

idx = zeros(size(c));
idx(1:3,:) = c(1:3,:)<17;
c(idx==1) = 0

这篇关于Matlab中的范围选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆