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
0 个评论
回答(1 个)
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!