Replace row of matrix with vector by logical indexing
6 views (last 30 days)
Show older comments
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 Comments
Answers (2)
Andrei Bobrov
on 1 Sep 2019
Edited: Andrei Bobrov
on 2 Sep 2019
a = 101:120;
lo = a(:) > 112;
b(lo,:) = lo(lo>0).*[55,56,57,58,59];
2 Comments
Guillaume
on 1 Sep 2019
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 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!