Mahm00d
Mahm00d

Reputation: 3921

Using matrix rows as index range on a vector?

I have this matrix:

A = [1 3
    5 7
    9 10];

And this vector:

B = zeros(1,10);

Now I want to change the elements in the ranges of [1:3],[5:7] and [9:10] to 1 . So, to get this:

C = [1 1 1 0 1 1 1 0 1 1];

I tried:

B(A(:,1):A(:,2)) = 1;

but it just changes the zeros in the first range.

Can it be done without a for loop?

Thanks.

Upvotes: 1

Views: 55

Answers (3)

snarfree
snarfree

Reputation: 109

Hello you can try this:

B([A(1,1):A(1,2) A(2,1):A(2,2) A(3,1):A(3,2)]) = 1;

Upvotes: 0

Nigel
Nigel

Reputation: 354

Would something like this be appropriate?

>> f = @(x)(any(A(:,1)<=x & x<=A(:,2)));
>> i = 1:length(B)

i =

     1     2     3     4     5     6     7     8     9    10

>> arrayfun(f,i)

ans =

     1     1     1     0     1     1     1     0     1     1

Upvotes: 2

Oleg
Oleg

Reputation: 10676

The first column of A are starting positions and the second one are ending positions of each sequence of 1s. To denote a beginning use 1 and for the end -1, then cumsum().

% Preallocate
N = 10;
B = zeros(1,N);

B(A(:,1)) = 1
B =
     1     0     0     0     1     0     0     0     1     0
B(A(:,2)+1) = -1
B =
     1     0     0    -1     1     0     0    -1     1     0    -1
B = cumsum(B)
B =
     1     1     1     0     1     1     1     0     1     1     0
B(1:N)
ans =
     1     1     1     0     1     1     1     0     1     1

Upvotes: 4

Related Questions