MATLAB Answers

How to replace certain rows in a matrix with the same row vector?

10 views (last 30 days)
Isobel
Isobel on 18 Mar 2016
Commented: Isobel on 18 Mar 2016
I have a 100 x 3 matrix that I first fill with a repeating row vector:
colours = repmat([1, 0, 0], 100, 1)
I then want to replace selected, non-contiguous rows of the matrix with a different row vector. Which rows should be replaced is determined by a 100 x 1 logical. The following code gives a dimension mismatch (I understand why):
colours(logical(data(:, 18)), :) = [0 1 0];
Is there a way to achieve this without a loop?

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 18 Mar 2016
Edited: Stephen Cobeldick on 18 Mar 2016
Here is one easy way:
new = [0,1,0];
idx = logical(data(:,18));
colours(idx,1) = new(1);
colours(idx,2) = new(2);
colours(idx,3) = new(3);
Although this is not a general solution for an arbitrary number of columns, because the color data will only ever have three columns it is quite acceptable to explicitly allocate to each column.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!