Array manipulation ... a better way?

조회 수: 2 (최근 30일)
Damo Nair
Damo Nair 2013년 1월 23일
Hi,
I have a 2d array with 3 columns that look something like this ...
states
1 4 9
5 10 60
1 61 92
5 93 157
1 158 229
5 230 274
if the value in column 1 is 1 then I have to find the min value from a new array p, min(p(4:9)) & if its 5, the max, max(p(10:60)) for that value range listed in columns 2 & 3. The values in col. 1 take on values of either 1 or 5 only.
Now, I'm doing this in a loop in loop like ...
if states(i,1) == 1; q(i) = min(p(states(i,2):states(i,3)));
if states(i,1) == 5; q(i) = max(p(states(i,2):states(i,3)));
Isn't there a better way to do this?
Thanks
Damo.
  댓글 수: 1
Walter Roberson
Walter Roberson 2013년 1월 23일
Note: please only indent your code, and not your text description. I have edited for clarity.

댓글을 달려면 로그인하십시오.

채택된 답변

Sarah Wait Zaranek
Sarah Wait Zaranek 2013년 1월 25일
You can do this with logical indexing (and not a for-loop)
q = zeros(length(p(:,1)),1);
Find where the first column is equal to 1.
idx1 = p(:,1) == 1;
Find the min of the next two columns where first column is equal to 1
q(idx1) = min(p(idx1,2:3),[],2);
Find where the first column is equal to 5
idx2 = p(:,1) == 5;
Find the min of the next two columns when first column is equal to 5
q(idx2) = max(p(idx2,2:3),[],2);
  댓글 수: 2
Sarah Wait Zaranek
Sarah Wait Zaranek 2013년 1월 25일
I didn't see that you were indexing into another variable with your p values, but the idea should still hold.
Damo Nair
Damo Nair 2013년 1월 26일
Thanks, Sarah.
Your method does indeed work! I can reference the 2nd array with those indices. Don't know why these things elude me sometimes :)
Have a good day.
Damo.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by