Reputation: 4899
I have a 10x5
double matrix mat
. I also have a 1x5
row vector start_rows
. In mat
I would like to replace all numbers from specific rows onwards using start_rows
. I could use a loop and replace all the numbers column by column. However, I'm sure there is some vectorized solution.
mat = nan(10, 5);
start_rows = [3,5,1,7,2];
% How to avoid that loop
for idx = 1 : numel(start_rows)
mat(start_rows(idx):end, idx) = 1;
end
Upvotes: 1
Views: 89
Reputation: 24179
This can be solved comparing an array of the following form to your start_rows
vector:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
10 10 10 10 10
which will return a logical array for when the condition is met (this uses broadcasting AKA implicit expansion).
If mat
always contains zeros, and you're replacing with ones:
(1:size(mat,1)).'+ mat >= start_rows;
If mat
is nonzero:
(1:size(mat,1)).'+ 0*mat >= start_rows; % option 1
(1:size(mat,1)).'+ zeros(size(mat)) >= start_rows; % option 2
If replacing with values other than 1
(or true
):
((1:size(mat,1)).'+ 0*mat >= start_rows) * newVal;
Upvotes: 2