Filling an array with indices without loops/if-statements

2 次查看(过去 30 天)
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