Archis Likhitkar
Archis Likhitkar

Reputation: 11

Solving a Simple Sorting Problem in MATLAB

I have been given this problem in a MATLAB course I am doing. The instructor's solution provided there is wrong, and I have been struggling with the same problem for hours as I am a beginner who has just started coding (a science student here).

Consider a one-dimensional matrix A such as A = \[5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 \]. Show the percentage frequencies of unique elements in the matrix A in descending order.

Hint: Use the functions tabulate and sort.

How do I solve this problem using only tabulate, sort, and find functions (find is for eliminating zero frequency elements in tabulate table, which my instructor did not do)?

I tried first extracting the indices of non-zero elements in the percentage column of tabulating table using the find function, which I succeeded in doing using the following:

A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);
C = find(B(:,3) > 0) 

But I am now struggling to return the values corresponding to the 3rd column of B using indices in C. Please help. Also please give me some alternative syntax where one can easily make a vector out of non-zero elements of a row or column easily by omitting the zeroes in that vector if it exists. Rest of the problem I'll do by myself.

Upvotes: 0

Views: 155

Answers (1)

Skapis9999
Skapis9999

Reputation: 454

With your find command, you are just finding the indices of the matrix and not the values themselves.

So you either will do something like this:

A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);

for i = 1:size(B,1)-1
    if B(i,3) == 0
        B(i,:) = [];
    end
end

sortrows(B,3,'descend')

where you remove the 0 value's row.

Or since you have all the numbers with none-zero frequency you can ask for their rows. Like this:

A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);
C = find(B(:,3) > 0); 
sortrows(B(C(:),:),3,'descend')

in a bit more elegant way. B(C(:),:) calls all the rows with first indices the indices of matrix C. Which is exactly what you are asking for. While at the same time you sort your matrix based on row 3 at a descending order.

Upvotes: 1

Related Questions