MATLAB Answers

0

Replace row of matrix with vector by logical indexing

Asked by Aaron Rietman on 1 Sep 2019
Latest activity Commented on by Andrei Bobrov
on 2 Sep 2019
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

Sign in to comment.

Products


Release

R2018b

2 Answers

Answer by Andrei Bobrov
on 1 Sep 2019
Edited by Andrei Bobrov
on 2 Sep 2019

a = 101:120;
lo = a(:) > 112;
b(lo,:) = lo(lo>0).*[55,56,57,58,59];

  2 Comments

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]
I'm fixed my answer.

Sign in to comment.


Answer by 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

Sign in to comment.