Filling an array with indices without loops/if-statements

조회 수: 2 (최근 30일)
Melissa Lopez
Melissa Lopez 2019년 2월 11일
댓글: Melissa Lopez 2019년 2월 11일
I'm trying to develop this code where I have to fill an array with indices that meet the conditions of habitable planets without using any sort of if-statements or loops. I have no idea how to tacke this problem and any hints would be greatly appreciated. I did try one way, as shown below but I'm sure I'm not doing it correctly.
ind_habit=[(rad > 0.4 && rad < 2.5) && (orb > 90 && orb < 802) && (temp >186 && temp <295) && (dist > 0.74 && dist < 1.84)];
%fill this array with the indices of all planets that are potentially habitable
%%Must meet below requirements:
% % rad > 0.4 && rad < 2.5
% % orb > 90 && orb < 802
% % temp >186 %% temp <295
% % dist > 0.74 && dist < 1.84

답변 (1개)

Kevin Phung
Kevin Phung 2019년 2월 11일
편집: Kevin Phung 2019년 2월 11일
if T is your table with rows of planets, and columns of rad, orb, and temp, you can use logical indexing:
% % rad > 0.4 && rad < 2.5
% % orb > 90 && orb < 802
% % temp >186 %% temp <295
% % dist > 0.74 && dist < 1.84
rad_condition = and(T.rad > 0.4, T.rad < 2.5);
orb_condition = and(T.orb > 90, T.org < 802);
temp_condition = and(T.temp > 186,T.temp < 295);
dist_condition = and(T.dist > 0.74, T.dist < 1.84);
%combine these conditions into logical matrix
C = [rad_condition orb_condition temp_condition dist_condition];
ind = find(any(C,2)) %any(C,2) locates only the rows where all the values are true,
% find() then returns those indices.
T(ind,:) % will list all habitable
  댓글 수: 1
Melissa Lopez
Melissa Lopez 2019년 2월 11일
Thanks. I found this way too, I think both would give out the same output.
ind_habit= [[rad > 0.4 & rad < 2.5],[orb > 90 & orb < 802],[temp >186 & temp <295],[dist > 0.74 & dist < 1.84]];

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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by