How do I avoid creating intermediate variables?

조회 수: 1 (최근 30일)
AJP
AJP 2011년 5월 30일
Say I have a vector of data x and a function f(x).
Now say I want to evaluate f(x) only for x>2, so I do:
ind=x>2; y=f(x(ind));
Now say I want to find y>5;
ind2=y>5;
Now how can I use this information to get the x values corresponding to the y>5 values, WITHOUT using this crude method where I create an intermediate variable:
x_intermediate = x(ind1); % I want to avoid creating this
x_answer = x_intermediate(ind2);

채택된 답변

Walter Roberson
Walter Roberson 2011년 5월 30일
ind1 = find(x>2);
y = f(x(ind1));
x(ind1(y>5))

추가 답변 (2개)

Matt Fig
Matt Fig 2011년 5월 30일
Is your complaint about the extra typing, or the extra variable in the workspace? If the latter, then one way to avoid this kind of thing in general is:
x_answer = x(ind1); % This will be overwritten.
x_answer = x_answer(ind2);
This strategy will serve you beyond this specific problem.

Andrei Bobrov
Andrei Bobrov 2011년 5월 30일
xy = [x f(x)];
out = xy(xy(:,1)>2&xy(:,2)>5,:)
  댓글 수: 1
AJP
AJP 2011년 5월 30일
Perhaps I should clarify that the x vector is very large. I therefore want to avoid the creation of any extra variables because they essentially just repeat data already stored in x.
Essentially what I want to do is to use the information in ind1 and ind2 to "filter" the x values so I can pass these filtered values to another, later function.

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

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by