通过向量访问具有索引的矩阵 [英] Access to a matrix with indexes from a vector
问题描述
我有一个矩阵a(16x3)和一个向量b(16x1). b显示了矩阵a中每行有多少个有效值.
I have a matrix a(16x3) and a vector b(16x1). b shows how many of the values in the matrix a are valid per row.
a = magic(3)
a =
8 1 6
3 5 7
4 9 2
b = [1;3;2]
b =
1
3
2
我正在尝试将无效值设置为NaN:
What I'm trying to do is setting the invalid values to NaN:
a(:,b+1:end)=NaN
结果是:
a =
8 NaN NaN
3 NaN NaN
4 NaN NaN
但是我期望的是:
a =
8 NaN NaN
3 5 7
4 9 NaN
这是怎么了?
推荐答案
bsxfun
和@gt
创建这些元素的逻辑掩码,然后
Perfect setup for bsxfun
with @gt
to create a logical mask of those elements and then logically index into a
to set them as NaNs
-
a(bsxfun(@gt,1:size(a,2),b(:))) = NaN
针对一般m x n
案例的示例运行-
Sample run for a generic m x n
case -
a =
2 9 7 2 9
5 7 2 9 5
7 5 1 3 1
8 1 6 2 2
b =
1
4
3
2
a =
2 NaN NaN NaN NaN
5 7 2 9 NaN
7 5 1 NaN NaN
8 1 NaN NaN NaN
在这里,logical mask
是-
>> bsxfun(@gt,1:size(a,2),b(:))
ans =
0 1 1 1 1
0 0 0 0 1
0 0 0 1 1
0 0 1 1 1
因此,1s
用于选择 to be
设置为NaNs
的元素,其余元素被触摸 not to be
或改变了.
So, the 1s
were used to select the elements that were to be
set as NaNs
and rest of the elements were not to be
touched or changed.
您也可以使用a(~bsxfun(@le,1:size(a,2),b(:))) = NaN
来达到相同的效果.
You can also use a(~bsxfun(@le,1:size(a,2),b(:))) = NaN
for the same effect.
这篇关于通过向量访问具有索引的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!