Filling an array with indices without loops/if-statements
2 views (last 30 days)
Show older comments
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 Comments
Answers (1)
Kevin Phung
on 11 Feb 2019
Edited: Kevin Phung
on 11 Feb 2019
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
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!