How to print a certain amount of elements in an array?

7 views (last 30 days)
If I have an array of student ID in column1 and GPAs in column2
EX:
Info = [52211 3.55; 52922 1.79; 51939 3.33; 12140 0.81]
How can I print the first 2 elements in the array based on the GPA??
  4 Comments
Image Analyst
Image Analyst on 9 Oct 2018
I could copy and paste and run Jan's code all in one shot since it defined the Info matrix. Yours would have required two copy and paste operations to try it out. I also like explicit variable names, like index rather than id, though I probably would have chosen selectedRows rather than index. Though you did choose a good name for "students_gpas". I like how he showed the Info variable as the 2-D matrix that it is, rather than the one-liner code the poster used. Not sure the sort() was needed but that was a guess on Jan's part since the poster was so vague about what was wanted. I also like his style of putting spaces around operators (equals, commas, etc.) to make the code more readable.
I like your enthusiasm. Keep it up. We can always use more good answerers here.
madhan ravi
madhan ravi on 9 Oct 2018
Thank you for being explicit @ sir Image Analyst will work on it from next time :).

Sign in to comment.

Accepted Answer

madhan ravi
madhan ravi on 8 Oct 2018
Edited: madhan ravi on 9 Oct 2018
An example:
id = Info(:,2) > 3
students_gpas = Info(id,:) %students whose GPA is more than 3
  5 Comments

Sign in to comment.

More Answers (1)

Jan
Jan on 8 Oct 2018
Edited: Jan on 8 Oct 2018
I'm not sure, what you are asking for, but a bold try:
Info = [52211 3.55; ...
52922 1.79;
51939 3.33;
12140 0.81];
[~, index] = sort(Info(:, 2));
Output = Info(index(1:2), :)
This is the part of the matrix Info with the 2 smallest values in the 2nd column.
  2 Comments
PJ
PJ on 8 Oct 2018
Edited: PJ on 8 Oct 2018
Essentially, I have a 100x2 array. Column 1 is Student IDs and Column 2 is GPA. I want to create a function in which I can print the first 25 GPAs in the array.
Jan
Jan on 8 Oct 2018
Then use my code with:
Output = Info(index(1:25), :)
if "the first" means the 25 smallest elements in sorted order.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!