【matlab】出数组中符合条件的数并赋值matlab中寻出array中符合要求的数的位置,并赋值
1.直接条件赋值
a = randn(10)
>>>
a =
0.8404 -2.1384 2.9080 -0.3538 0.0229 0.5201 -0.2938 -1.3320 -1.3617 -0.1952
-0.8880 -0.8396 0.8252 -0.8236 -0.2620 -0.0200 -0.8479 -2.3299 0.4550 -0.2176
0.1001 1.3546 1.3790 -1.5771 -1.7502 -0.0348 -1.1201 -1.4491 -0.8487 -0.3031
-0.5445 -1.0722 -1.0582 0.5080 -0.2857 -0.7982 2.5260 0.3335 -0.3349 0.0230
0.3035 0.9610 -0.4686 0.2820 -0.8314 1.0187 1.6555 0.3914 0.5528 0.0513
-0.6003 0.1240 -0.2725 0.0335 -0.9792 -0.1332 0.3075 0.4517 1.0391 0.8261
0.4900 1.4367 1.0984 -1.3337 -1.1564 -0.7145 -1.2571 -0.1303 -1.1176 1.5270
0.7394 -1.9609 -0.2779 1.1275 -0.5336 1.3514 -0.8655 0.1837 1.2607 0.4669
1.7119 -0.1977 0.7015 0.3502 -
2.0026 -0.2248 -0.1765 -0.4762 0.6601 -0.2097
-0.1941 -1.2078 -2.0518 -0.2991 0.9642 -0.5890 0.7914 0.8620 -0.0679 0.6252
% 寻⼤于零的位置
a>0
>>>
ans =
1 0 1 0 1 1 0 0 0 0
0 0 1 0 0 0 0 0 1 0
1 1 1 0 0 0 0 0 0 0
0 0 0 1 0 0 1 1 0 1
1 1 0 1 0 1 1 1 1 1
0 1 0 1 0 0 1 1 1 1
1 1 1 0 0 0 0 0 0 1
1 0 0 1 0 1 0 1 1 1
1 0 1 1 0 0 0 0 1 0
0 0 0 0 1 0 1 1 0 1
% 将⼩于零的位置都赋值为0
b = a;
b(a<0) = 0
matlab数组赋值>>>
b =
0.8404 0 2.9080 0 0.0229 0.5201 0 0 0 0
0 0 0.8252 0 0 0 0 0 0.4550 0
0.1001 1.3546 1.3790 0 0 0 0 0 0 0
0 0 0 0.5080 0 0 2.5260 0.3335 0 0.0230
0.3035 0.9610 0 0.2820 0 1.0187 1.6555 0.3914 0.5528 0.0513
0 0.1240 0 0.0335 0 0 0.3075 0.4517 1.0391 0.8261
0.4900 1.4367 1.0984 0 0 0 0 0 0 1.5270
0.7394 0 0 1.1275 0 1.3514 0 0.1837 1.2607 0.4669
1.7119 0 0.7015 0.3502 0 0 0 0 0.6601 0
0 0 0 0 0.9642 0 0.7914 0.8620 0 0.6252
2.使⽤find⽅法
[row,col] = find(a>0); %输出满⾜条件的位置
>>>
[row,col]
ans =
1 1
3 1
5 1
7 1
8 1
9 1
3 2
5 2
6 2
7 2
1 3
2 3
3 3
7 3
9 3
4 4
5 4
6 4
8 4
9 4
1 5
10 5
1 6
5 6
8 6
4 7
5 7
6 7
10 7
4 8
5 8
6 8
8 8
10 8
2 9
5 9
6 9
8 9
9 9
4 10
5 10
6 10
7 10
8 10
10 10
% 将所有⼩于零的位置替换为0
c = a;
c(find(c<0)) = 0
>>>
c =
0.8404 0 2.9080 0 0.0229 0.5201 0 0 0 0
0 0 0.8252 0 0 0 0 0 0.4550 0
0.1001 1.3546 1.3790 0 0 0 0 0 0 0
0 0 0 0.5080 0 0 2.5260 0.3335 0 0.0230
0.3035 0.9610 0 0.2820 0 1.0187 1.6555 0.3914 0.5528 0.0513 0 0.1240 0 0.0335 0 0 0.3075 0.4517 1.0391 0.8261
0.4900 1.4367 1.0984 0 0 0 0 0 0 1.5270
0.7394 0 0 1.1275 0 1.3514 0 0.1837 1.2607 0.4669
1.7119 0 0.7015 0.3502 0 0 0 0 0.6601 0
0 0 0 0 0.9642 0 0.7914 0.8620 0 0.6252
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论