Replace row of matrix with vector by logical indexing
4 次查看(过去 30 天)
显示 更早的评论
I can do:
a = 101:120;
b = zeros(20,1);
b(a>112) = 55;
and it will give me b as a 1D vector with 55 in the places that a > 112.
But:
a = 101:120;
b = zeros(20,5);
b(a>112) = [55,56,57,58,59];
is no good. It complains about the right side vector being 1x5 and the logical indexed side 8x5. How would I go about placing that 5-element vector in all the indexed rows in b? In my case, all sizes and values are unknown, so repmat won't work, manually setting b(a>112,1), b(a>112,2), etc... won't work. I would prefer to not use a big loop, as this needs to be done many times.
0 个评论
回答(2 个)
Andrei Bobrov
2019-9-1
编辑:Andrei Bobrov
2019-9-2
a = 101:120;
lo = a(:) > 112;
b(lo,:) = lo(lo>0).*[55,56,57,58,59];
Guillaume
2019-9-1
a = 101:120; %a should really be a column vector to start with, if it's meant to work along the rows of b
b = reshape(1:100, 20, 5);
replacement = [55, 56, 57, 58, 59];
mask = a' > 112;
b(repmat(mask, 1, size(b, 2))) = repmat(replacement, nnz(mask), 1)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!