Sohaib
Sohaib

Reputation: 4694

Add to specific indices to an array based on a condition in matlab

I have an array S 440x120 in dimensions. There is another array T 440x1.

I need to append say rows of S to another array T1 based on the following conditions

  1. The rows appended must be from index say 100 to 200 in S.
  2. Only those rows with T(100:200)==1 should be included. This means that if T(100)=0 then S(100,:) should not be included and if T(101)=1 then S(101,:) should be included.

I tried using the following but it failed due to obvious reasons as it includes from the first index and not from the 100th.

T1=S(T(100:200)==1,:);

Is there a shorter way of doing this in matlab apart from writing a whole loop? Thanks for your answers.

Upvotes: 1

Views: 238

Answers (3)

Luis Mendo
Luis Mendo

Reputation: 112669

You almost have it. You only need to add an offset to the numeric (not logical) indices:

N = 100;
M = 200;
result = S(N-1+find(T(N:M)==1),:);

Upvotes: 2

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Here you go:

idx = find(T==1);
idx = idx(idx>=100 & idx<=200);

S(idx,:)

Upvotes: 1

3lectrologos
3lectrologos

Reputation: 9642

How about T1=S([zeros(99,1); T(100:200)]==1,:);?

Upvotes: 2

Related Questions