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.

回答(2 个)

Andrei Bobrov
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];
  2 个评论
Aaron Rietman
Aaron Rietman 2019-9-1
Sorry, I guess I didn't ask the question correctly. b should stay unchanged at the other locations. Let me rewrite my non-working example to clarify:
a = 101:120;
b = [(some arbitrary 20 row, 5 column matrix)]
b(a>112) = [55,56,57,58,59];
% now b is the same arbitrary matrix, except the last 8 rows are all [55,56,57,58,59]

请先登录,再进行评论。


Guillaume
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)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by